nodejs read json file code example
Example 1: read json file nodejs
const fs = require('fs');
const path = require('path');
let rawdata = fs.readFileSync(path.resolve(__dirname, 'student.json'));
let student = JSON.parse(rawdata);
console.log(student);
Example 2: write json file nodejs
const fs = require('fs');
const path = require('path');
let student = {
name: 'Mike',
age: 23,
gender: 'Male',
department: 'English',
car: 'Honda'
};
fs.writeFileSync(path.resolve(__dirname, 'student.json'), JSON.stringify(student));
Example 3: read json using fs
let jsonData = require('./student.json');
console.log(jsonData);
Example 4: 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 5: how to use json file in nodejs
var fs = require("fs");
console.log("\n *START* \n");
var content = fs.readFileSync("content.txt");
console.log("Output Content : \n"+ content);
console.log("\n *EXIT* \n");