2015-02-10 98 views
-2

我試圖保存request.headers,但它在txt文件上一直返回[object Object]無法在Node.JS中保存變量

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); 
+0

你想什麼其他格式,如果你不喜歡的'[對象的對象]'系列化使用? – Bergi 2015-02-10 17:20:57

回答

1

使用JSON.stringify

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

謝謝!現在我的另一個問題是代碼被保存兩次 – Royce 2015-02-10 17:49:58

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!'); 
});