简体   繁体   中英

Node.js : Write new data to an existing json file

I'm trying to add data to an existing json file (codes below). When I access the locahost, the new piece of data shows up, however, when I check the data (users.json), the new piece of data (ie user4) isn't there.

Does anyone know what's wrong with the code? Thank you!

var express = require('express');
var app = express();
var fs = require("fs");

var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}

app.get('/addUser', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       data["user4"] = user["user4"];
       console.log( data );
       res.end( JSON.stringify(data));
   });
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)

})

EDIT: I added fs.writeFile(...) (codes below). After running the code, the only content of the uers.json file is: utf8

var express = require('express');
var app = express();
var fs = require("fs");

var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}

app.get('/addUser', function (req, res) {
   // First read existing users.
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
        data = JSON.parse( data );
        data["user4"] = user["user4"];
        console.log( data );
//       res.end( JSON.stringify(data));
        data = JSON.stringify(data);
        fs.writeFile(__dirname+"/"+"users.json", "utf8", function(err,data){
            if (err){
                console.log(err);
            };
            res.end(data);
        });
   });
})

To write to a file you should use fs.writeFile .

fs.writeFile(__dirname + "/" + "users.json", user["user4"], 'utf8', function()
{
  // do anything here you want to do after writing the data to the file
});

I have passed data to writeFile so that it may write the information in data variable to JSON

fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { 
   data = JSON.parse( data );
   data["user4"] = user["user4"];
   console.log( data );
   data = JSON.stringify(data);

   fs.writeFile(__dirname + "/" + "users.json", data , 'utf8', function(err,data) {
       if (err){
           console.log(err);
       };
       res.end(data);
    });  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM