无法在Node.JS中保存变量

时间:2015-02-10 17:07:56

标签: javascript node.js

我试图保存request.headers,但它一直在txt文件上返回[object Object]

var http = require("http");
url = require("url");
fs = require("fs");

var events = require('events');
var even = new events.EventEmitter();

http.createServer(function(request, response) {

  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
  var head = request.headers;


var append = function(data ){
fs.appendFile('message.txt', data, function (err) {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');

});
}
var time = new Date();
console.log(head);
append(head + ": "+ time+ "\n");
}).listen(8888);

2 个答案:

答案 0 :(得分:1)

使用JSON.stringify

append(JSON.stringify(head) + ": " + time + "\n");

答案 1 :(得分:0)

保存之前,您可以将对象保存到json示例。

fs.appendFile('message.txt', JSON.stringify(data), function (err) {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});