簡體   English   中英

fs.appendFile返回[對象Object]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM