MySQL 和 fs.writeFile (Node JS) 有问题

Having trouble with MySQL and fs.writeFile (Node JS)

我在使用 Node JS MySQL 和 fs 时遇到了一些问题。 我正在尝试做的是将数据从我的数据库提取到本地 txt 文件。 对于数据库中的每个 ID,我希望它像 \n

这样向下一行

我的代码:

 connection.query(`SELECT * FROM appmsg`, function(error, results, fields) {
      try{
          fs.writeFile('./commands/utils/apps.txt', JSON.stringify(results.join("\n")), function (err) {
            if(err) throw err;
            console.log("Saved!");
          })

        }
        catch(err){
          console.log(err)
        }
      })

txt 文件中:

"[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]\n[object Object]"

期待回复。 提前致谢:)

只需使用 results.map(result => JSON.stringify(result)).join("\n") 而不是 JSON.stringify(results.join("\n"))

这个问题是因为您将数组转换为字符串results.join("\n")。因此,当您将数组转换为字符串时,他会将每个对象转换为字符串,因此它将是 [object Object]。您需要将每个对象转换为 JSON 然后将所有数组转换为字符串。可以根据需要保存数据。