![](/img/trans.png)
[英]Have a JSON file on server with a Array of objects and want to push an object to it with fs.appendFile
[英]fs.appendFile returning [object Object]
console.log正確返回req.query(request.query),如{名稱:'sean',注釋:'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
和AFAIK)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.