console.log 正确返回 req.query (request.query),如 { name: 'sean', comments: 'Hey' }。但是当我尝试使用 fs.appendFile 将其写入文件时,它将其写入为 [object Object]。这是服务器代码:
app.get('/', function (req, res) {
var rq = req.query //Write req.query to a variable
console.log("received: ", rq) //This returns correctly
fs.appendFile('comments.txt', rq, function (req, err) { //This is where object Object is written
if (err) throw err;
console.log("written: ", rq) //This returns correctly
});
res.header('Content-type', 'text/html');
return res.end('<h1>Hello, World!</h1>');
});
有什么想法吗?谢谢。
最佳答案
您需要将 Javascript 对象序列化为字符串,然后才能将它们正确写入文件。一种方法是使用 JSON.stringify():
fs.appendFile('comments.txt', JSON.stringify(rq), function(err) {
...
});
(fs.appendFile()
的回调仅接收一个参数,err
,据我所知)
关于javascript - fs.appendFile 返回 [object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31836455/