I'm having some trouble with Node JS MySQL and fs.
What I'm trying to do, is extracting data from my database to a local txt
file.
For each ID in the database, I want it to go a line down like \n
My code:
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)
}
})
In the txt
file:
"[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]"
Looking forward to a response. Thanks in advance :)
Just use results.map(result => JSON.stringify(result)).join("\n")
instead of JSON.stringify(results.join("\n"))
.
This issue because you convert the array to string results.join("\n")
. so when you convert array to string he will convert each object to string so it will be [object Object]
. you need to convert each object to JSON then convert all array to string. to can save data as you need.