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

3

7

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.

Eastwards answered 3/11, 2020 at 1:37 Comment(4)
Very thorough article on this here: stackabuse.com/reading-and-writing-json-files-with-node-jsAmaras
@thanhdx - wrong context - not from the browser, from NodeJSSalvadorsalvadore
@RandyCasburn Yeah, I've just restract the flag. Sorry.Rovelli
Here's a better one: #42671821Salvadorsalvadore
S
21

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/

Surprise answered 3/11, 2020 at 1:46 Comment(0)
A
2

Use NodeJS File System https://nodejs.org/dist/latest-v14.x/docs/api/fs.html.

Here I have used writeFileSync API to write to file and readFileSync to read from file. Also, when writing don't forget to JSON.stringify(data) because you are writing the data to a JSON file.

const fs = require("fs");
const path = require("path");

// Write Data
const data = {
"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>"
        }
      }
    }
  }
};

fs.writeFileSync(path.join(__dirname, "outputfilepath", "outputfile.json"), JSON.stringify(data), "utf8");

// Read data
const rData = fs.readFileSync(path.join(__dirname, "outputfilepath", "outputfile.json"), "utf8");
const jsonData = JSON.parse(rData);

Here is the working example, https://repl.it/repls/OutrageousInbornBruteforceprogramming#index.js

Atabrine answered 3/11, 2020 at 1:43 Comment(0)
N
2

you can do something like this for reading:

const fs = require('fs')
function jsonReader(filePath, cb) {
    fs.readFile(filePath, (err, fileData) => {
        if (err) {
            return cb && cb(err)
        }
        try {
            const object = JSON.parse(fileData)
            return cb && cb(null, object)
        } catch(err) {
            return cb && cb(err)
        }
    })
}
jsonReader('./customer.json', (err, customer) => {
    if (err) {
        console.log(err)
        return
    }
    console.log(customer.address) // => "Infinity Loop Drive"
})

and like this for writing:

const fs = require('fs')
const customer = {
    name: "Newbie Co.",
    order_count: 0,
    address: "Po Box City",
}
const jsonString = JSON.stringify(customer)
fs.writeFile('./newCustomer.json', jsonString, err => {
    if (err) {
        console.log('Error writing file', err)
    } else {
        console.log('Successfully wrote file')
    }
})
Newsy answered 6/11, 2020 at 4:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.