我正在尝试使用node.js在文件上写一个数组,并且我已经使用angular实现了这一点,您可以检查此问题中的其余代码。
当我发送一个数组时,文件看起来像这样:[object Object],...
当我在内部发送数组时JSON.stringify(myArr)
,它可以正确写入文件,但数据损坏并转换为对象。
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);
我正在尝试在文件上写入数组。
这应该工作正常:
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) {
// convert object to array
var arr = []
for (var index in req.body){
arr.push(req.body[index])
}
var jsonData = JSON.stringify(arr, null, 2);
console.log(jsonData);
fs.writeFile("./json/test.json", jsonData, function(err) {
res.json({ success: true });
});
});
var server = app.listen(3000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句