Search code examples
javascriptjsonread-write

How to read/write to a JSON file in node.js


I am fairly new to node.js and i am wondering how to (or even if) i can read and write to a JSON file. I am trying to create an accessible punishment history. Ideally i would want to be able to create something along the lines of this:

{
"punishments": {
    "users": {
      "<example user who has a punishment history>": {
        "punishment-1567346": {
          "punishment-id": "1567346",
          "punishment-type": "mute",
          "punishment-reason": "<reason>"
        },
        "punishment-1567347": {
          "punishment-id": "1567347",
          "punishment-type": "ban",
          "punishment-reason": "<reason>"
        }
      }
    }
  }
}

Then i would have a way to access the formatted punishment history. I genuinely have no clue where to start.


Solution

  • 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/