Sync:

var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));

Async:

var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
});
Answer from mihai on Stack Overflow
🌐
HeyNode
heynode.com › tutorial › readwrite-json-files-nodejs
Read/Write JSON Files with Node.js | HeyNode
The simplest way to read a JSON file is to require it. Passing require() with the path to a JSON file will synchronously read and parse the data into a JavaScript object.
🌐
LogRocket
blog.logrocket.com › home › reading and writing json files in node.js: a complete tutorial
Reading and writing JSON files in Node.js: A complete tutorial - LogRocket Blog
November 1, 2024 - In the Node runtime environment, you can use the built-in require function and fs modules to load or read JSON files. Because the require function is available for each module, you don’t need to require it.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-files-with-node-js
Reading and Writing JSON Files with Node.js
July 8, 2024 - However, we want to read the file in its JSON format, not the raw hex data. This is where the JSON.parse function comes into play. This function handles parsing the raw data, converts it to ASCII text, and parses the actual JSON data in to a JavaScript object.
🌐
Better Stack
betterstack.com › community › questions › using-node-how-to-read-json
Using node.js, How Do I Read a Json File into (Server) Memory? | Better Stack Community
const fs = require('fs'); // Specify the path to your JSON file const filePath = 'path/to/your/file.json'; // Read the JSON file fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading JSON file:', err); return; } // Parse the JSON data try { const jsonData = JSON.parse(data); // Now you have the JSON data in memory console.log('JSON Data:', jsonData); } catch (parseError) { console.error('Error parsing JSON:', parseError); } });
🌐
Educative
educative.io › answers › how-to-read-a-json-file-in-nodejs
How to read a JSON file in Node.js
Import the required modules for reading the file. The fs module will do this job for us. ... Store the path of the JSON file in a const variable.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-read-and-write-json-file-using-node-js
How to read and write JSON file using Node ? | GeeksforGeeks
January 7, 2025 - A straightforward way to read a JSON file in a Node JS file is by using the `require()` method to include it.
🌐
Futurestud.io
futurestud.io › tutorials › node-js-read-a-json-file
Node.js — Read a JSON File
Here’s a code sample reading ... the package object like you would use any other JavaScript object. The CommonJS module loader comes with the require() function. It’s a global function that you typically use to import files within other files....
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-import-local-json-file-data-to-my-javascript-variable
How to import local json file data to my JavaScript variable?
We have an employee.json file in a directory, within the same directory we have a js file, in which we want to import the content of the json file.The content of employees.json −employees.json"Employees" : [ { "userId":"ravjy", "jobTitleName
🌐
Quora
quora.com › How-can-I-load-data-from-a-JSON-file-into-a-variable-in-JavaScript-without-using-Ajax
How to load data from a JSON file into a variable in JavaScript without using Ajax - Quora
Answer (1 of 5): There are two ways of doing that: 1.Integrating the JSON file locally from your computer using script tags for ex: and then var mydata=mylocal.json Orelse There is this second method which will read the json file from another...
Top answer
1 of 3
24

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/

2 of 3
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

🌐
Attacomsian
attacomsian.com › blog › nodejs-read-write-json-files
How to read and write JSON files in Node.js
October 1, 2022 - All you need to do is pass the JSON file path to the require() method, and it will synchronously read and parse the JSON file and return a JSON object ready to be used:
🌐
Stack Overflow
mariokandut.com › how to read and write json files with node.js?
How to read and write JSON Files with Node.js?
March 21, 2022 - The file will be only read once, and it will be cached. This means, when requiring it again, the cached version will be returned. This is fine for static data, but not for data that changes dynamically. For dynamic data we have to use fs.readFile. Let's say we have a json file of a customer, and we want to print the customer address.
🌐
Codementor
codementor.io › community › how to use json files in node.js
How to Use JSON files in Node.js | Codementor
June 8, 2017 - The code which can be used for making Node.js automatically read the JSON file is shown below: ... Here, Node.js will parse the content to a particular JSON object and assign the same to the variable placed on the left hand side.
🌐
GoLinuxCloud
golinuxcloud.com › home › nodejs › 4 different ways to read json file in nodejs
4 different ways to read JSON file in NodeJS | GoLinuxCloud
January 26, 2022 - In the above code, you are reading the users.json file and passing in utf-8 encoding as an optional argument. When the file is read successfully, turn the JSON data into a JavaScript object using JSON.parse. This makes it possible o access the data received.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Create a Variable for an Imported JSON File
June 8, 2021 - Hey folks, I’m building out some basic vanilla js projects (randomized background color changer) and I figured out the code to accomplish that with an array variable INSIDE of my javascript file. I wanted to take it a s…
🌐
Geshan
geshan.com.np › blog › 2024 › 10 › nodejs-read-json-file
How to Read a JSON File Using Node.js
October 30, 2024 - Learn how to read a JSON file using Node.js. This post covers reading a JSON file synchronously and asynchronously using the fs module and fs-extra NPM package.