admin管理员组

文章数量:1286525

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.

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.

Share Improve this question asked Nov 3, 2020 at 1:37 iris87iris87 1531 gold badge2 silver badges11 bronze badges 4
  • Very thorough article on this here: stackabuse.com/reading-and-writing-json-files-with-node-js – Tony Drummond Commented Nov 3, 2020 at 1:41
  • @thanhdx - wrong context - not from the browser, from NodeJS – Randy Casburn Commented Nov 3, 2020 at 1:41
  • @RandyCasburn Yeah, I've just restract the flag. Sorry. – thanhdx Commented Nov 3, 2020 at 1:42
  • Here's a better one: stackoverflow.com/questions/42671321/… – Randy Casburn Commented Nov 3, 2020 at 1:43
Add a comment  | 

3 Answers 3

Reset to default 22

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/

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

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')
    }
})

本文标签: javascriptHow to readwrite to a JSON file in nodejsStack Overflow