Skip to content Skip to sidebar Skip to footer

Read And Write A Json File In Node.js

okay I have this json file: { 'joe': { 'name': 'joe', 'lastName': 'black' }, 'matt': { 'name': 'matt', 'lastName': 'damon' } }

Solution 1:

In node you can require json files:

var fs = require('fs');
var users = require('./names');

users.brad = {
  name: 'brad',
  lastName: 'pitt'
}

varstring = JSON.stringify(users,null,'\t');

fs.writeFile('./names.json',string,function(err) {
  if(err) returnconsole.error(err);
  console.log('done');
})

Optional async version without requiring:

var fs = require('fs');

fs.readFile('./names.json',{encoding: 'utf8'},function(err,data) {
  var users = JSON.parse(data);
   users.brad2 = { name: 'brad', lastName: 'pitt' };
  var string = JSON.stringify(users,null,'\t');

  fs.writeFile('./names.json',string,function(err) {
    if(err) returnconsole.error(err);
    console.log('done');
  })  
})

Solution 2:

The simple hint is: if you need to use process.nextTick, something is wrong. Leave that function to the library programmers! :)

Just move the function you call with nextTick to Until here...

nextTick does not wait until you read that file (that might take a few hundret ticks!), it just waits for the next tick. And that is available the nanosecond you call fs.read - because after fs.read the nodejs main loop is idle until either the kernel returns some information about that file or someone tells nodejs what to do on the next tick.

Post a Comment for "Read And Write A Json File In Node.js"