I'm trying to write an array as its on the file with node.js and i've used angular to achive this, you can inspect rest of the code from this question.
When i send an array, file seems like this: [object Object],...
When i send my array inside JSON.stringify(myArr), it writes properly on the file but data corrupts and converts as an a object.
json:
[{
"name" : "BigTitleLine1",
"content" : "APP TITLE 1"
}, {
"name" : "BigTitleLine2",
"content" : "APP TITLE 2"
}];
node.js:
var express = require('express'),
fs = require('fs'),
bodyParser = require('body-parser'),
app = express();
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.put('/update', function (req, res) {
console.log(req.body);
fs.writeFile("./json/test.json", req.body, function(err) {
res.json({ success: true });
});
// this returns true data on console
// but it writes [object Object],[object Object] to the file
var jsonData = JSON.stringify(req.body);
console.log(jsonData);
fs.writeFile("./json/test.json", jsonData, function(err) {
res.json({ success: true });
});
// this way writes well but
// it corrupts data and convert it to object:
//{"0":{"name":"BigTitleLine1","content":"APP TITLE 1"},"1":{"name":...}}
});
var server = app.listen(3000);
I'm trying to write array as its on the file.
fs.writeFile, i.e. only trying it with the secondfs.writeFile(where you're stringifying your payload). Because now you have two async write statements that are creating a race condition that could potentially cause weird stuff to happen.