how to write in json files node js code example
Example 1: HOW WRITE AND SAVE JSON FILE IN NODEJS
'use strict';
const fs = require('fs');
let student = {
name: 'Mike',
age: 23,
gender: 'Male',
department: 'English',
car: 'Honda'
};
let data = JSON.stringify(student, null, 2);
fs.writeFile('student-3.json', data, (err) => {
if (err) throw err;
console.log('Data written to file');
});
console.log('This is after the write call');
Example 2: how to use json file in nodejs
D:\NodeJs>node readsync.js
*START*
Output Content:
*EXIT*
var fs = require("fs");
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("jsoncontent.json");
var jsonContent = JSON.parse(contents);
console.log("User Name:", jsonContent.username);
console.log("Email:", jsonContent.email);
console.log("Password:", jsonContent.password);
log("\n *EXIT* \n");
Example 3: write json file in node js
function writeJsonFile(file, content) {
let jsonData = JSON.stringify(content)
fs.writeFileSync(file, jsonData)
}