如何使用fs在node.js Express上正确地将数组写入文件? [英] How to write array to a file properly on node.js express with fs?

查看:614
本文介绍了如何使用fs在node.js Express上正确地将数组写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node.js和

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.

当我发送一个数组时,文件看起来像这样:[object Object],...

When i send an array, file seems like this: [object Object],...

当我将数组发送到JSON.stringify(myArr)时,它可以正确写入文件,但数据损坏并转换为对象.

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.

推荐答案

这应该可以正常工作:

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

这篇关于如何使用fs在node.js Express上正确地将数组写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆