Skip to content

Instantly share code, notes, and snippets.

@zeynebozdem
Last active September 24, 2020 14:32
Show Gist options
  • Save zeynebozdem/e0508aaa3c11a22a8cc0774c47014503 to your computer and use it in GitHub Desktop.
Save zeynebozdem/e0508aaa3c11a22a8cc0774c47014503 to your computer and use it in GitHub Desktop.
How to write and read JSON file in Node.js?

Installation and Setup Instructions

  • Open terminal
  • mkdir NodeJsWriteReadExample
  • cd /NodeJsWriteReadExample
  • touch insert.js read.js data.json
  • copy codes below and past the files

For write data;

  • node insert.js

After write the data to data.json, You can read data;

  • node read.js
//this is a blank json file
const fs = require('fs');
const data = {
result : [{
id:'001',
message:{
messageID:'4567',
from:{
id:'4567',
first_name:'Jeson',
user_name: '@jeson'
},
message : 'hello how are you',
details : {
date: '23.03.2020',
time: '2.33 PM'
}
}
},
{
id:'002',
message:{
messageID:'3367',
from:{
id:'3367',
first_name:'Ayşe',
user_name: '@ayse'
},
message : 'hello im fine',
details : {
date: '22.09.2010',
time: '2.33 PM'
}
}
}]
}
const toJson = JSON.stringify(data);
fs.writeFileSync("data.json",toJson);
const fs = require('fs');
const doc = fs.readFileSync("data.json");
const tostring = doc.toString();
const data = JSON.parse(tostring);
console.log(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment