How to update a value in a json file and save it through node.js


Question

How do I update a value in a json file and save it through node.js? I have the file content:

var file_content = fs.readFileSync(filename);
var content = JSON.parse(file_content);
var val1 = content.val1;

Now I want to change the value of val1 and save it to the file.

1
60
5/21/2012 3:35:05 PM

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

var fs = require('fs');
var fileName = './file.json';
var file = require(fileName);

file.key = "new value";

fs.writeFile(fileName, JSON.stringify(file), function (err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

The caveat is that json is written to the file on one line and not prettified. ex:

{
  "key": "value"
}

will be...

{"key": "value"}

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2)

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

89
5/3/2016 1:47:59 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon