Skip to content Skip to sidebar Skip to footer

How To Write Array To A File Properly On Node.js Express With Fs?

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 s

Solution 1:

This should work fine:

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

Post a Comment for "How To Write Array To A File Properly On Node.js Express With Fs?"