how do i readwrite a json file in nodejs?

You can use a NodeJS built-in library called fs to do read/write operations.

Step #1 – Import fs

const fs = require('fs');

Step #2 – Read the file

let rawdata = fs.readFileSync('punishmenthistory.json');
let punishments= JSON.parse(rawdata);
console.log(punishments);

Now you can use the punishments variable to check the data inside the JSON File. Also, you can change the data but it only resides inside the variable for now.

Step #3 – Write to the File

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);

Full code:

const fs = require('fs');

let rawdata = fs.readFileSync('punishmenthistory.json');
let punishments= JSON.parse(rawdata);
console.log(punishments);

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);

References: https://stackabuse.com/reading-and-writing-json-files-with-node-js/

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top