如何在node.js上用fs表示正确地将数组写入文件?

时间:2015-08-28 12:25:20

标签: javascript arrays json node.js express

我正在尝试使用node.js和i've used angular to achive this, you can inspect rest of the code from this question.

在文件上编写一个数组

当我发送数组时,文件看起来像这样:[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);

我正在尝试将数组写为文件。

1 个答案:

答案 0 :(得分:3)

这应该可以正常工作:

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);