JSON in Node.js
Node.js is a JavaScript runtime that allows JavaScript to run on a computer or server — outside the browser. It is widely used to build backend systems, command-line tools, and APIs. When working with Node.js, JSON files are used constantly — for configuration (like package.json), for storing data, and for building REST APIs.
This topic covers how to read JSON from a file, write JSON to a file, and work with JSON data effectively in a Node.js environment.
The package.json File — JSON in Action
Every Node.js project has a package.json file at its root. This file is pure JSON and stores information about the project — its name, version, dependencies, and scripts. It is one of the most common examples of JSON used as a configuration file.
{
"name": "my-web-app",
"version": "1.0.0",
"description": "A simple Node.js application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2"
}
}Method 1 — Reading JSON Using require() (Synchronous)
The simplest way to read a local JSON file in Node.js is using require(). Node.js automatically parses the JSON file and returns it as a JavaScript object — no manual parsing is needed.
File: data/student.json
{
"name": "Tejas Kulkarni",
"rollNo": 204,
"course": "Data Science",
"grade": "A"
}File: index.js
const student = require("./data/student.json");
console.log(student.name); // Output: Tejas Kulkarni
console.log(student.course); // Output: Data Science
console.log(student.grade); // Output: Arequire() loads the file once and caches it. It is synchronous, meaning the code waits for the file to be read before continuing.
Method 2 — Reading JSON Using the fs Module (Asynchronous)
The built-in fs (file system) module provides more control over file reading. The asynchronous version reads the file in the background without blocking the rest of the program.
File: data/product.json
{
"productId": "P-501",
"name": "Wireless Keyboard",
"price": 1200,
"inStock": true
}File: readFile.js
const fs = require("fs");
fs.readFile("./data/product.json", "utf8", function(error, data) {
if (error) {
console.log("Error reading file: " + error);
return;
}
const product = JSON.parse(data);
console.log(product.name); // Output: Wireless Keyboard
console.log(product.price); // Output: 1200
});Here, the file is read as a text string, and then JSON.parse() converts it into a usable JavaScript object.
Method 3 — Reading JSON Using fs.readFileSync() (Synchronous)
For simpler scripts where blocking is acceptable, the synchronous version is cleaner:
const fs = require("fs");
const raw = fs.readFileSync("./data/product.json", "utf8");
const product = JSON.parse(raw);
console.log(product.name); // Output: Wireless Keyboard
console.log(product.inStock); // Output: trueWriting JSON to a File
To save data as a JSON file, convert the JavaScript object to a JSON string using JSON.stringify(), then write it using fs.writeFile():
const fs = require("fs");
const newEmployee = {
id: 1025,
name: "Kaveri Nambiar",
department: "Finance",
salary: 55000
};
const jsonContent = JSON.stringify(newEmployee, null, 2);
fs.writeFile("./data/employee.json", jsonContent, "utf8", function(error) {
if (error) {
console.log("Error writing file: " + error);
return;
}
console.log("employee.json has been saved successfully.");
});The third argument null, 2 in JSON.stringify() makes the saved file human-readable with 2-space indentation.
Updating a JSON File
To update data in an existing JSON file, read it, modify the object, then write it back:
const fs = require("fs");
// Step 1: Read the existing file
const raw = fs.readFileSync("./data/employee.json", "utf8");
const employee = JSON.parse(raw);
// Step 2: Modify the data
employee.salary = 62000;
employee.department = "Accounts";
// Step 3: Write the updated data back
fs.writeFileSync("./data/employee.json", JSON.stringify(employee, null, 2), "utf8");
console.log("Employee data updated.");Reading a JSON File That Contains an Array
File: data/students.json
[
{ "name": "Aryan", "score": 88 },
{ "name": "Meghna", "score": 92 },
{ "name": "Pranav", "score": 75 }
]Reading and looping through the array:
const fs = require("fs");
const raw = fs.readFileSync("./data/students.json", "utf8");
const students = JSON.parse(raw);
students.forEach(function(student) {
console.log(student.name + ": " + student.score);
});
// Output:
// Aryan: 88
// Meghna: 92
// Pranav: 75Using async/await with fs.promises
Modern Node.js supports promise-based file operations, making async file reading cleaner:
const fs = require("fs").promises;
async function loadProduct() {
try {
const raw = await fs.readFile("./data/product.json", "utf8");
const product = JSON.parse(raw);
console.log("Product: " + product.name);
} catch (error) {
console.log("Error: " + error);
}
}
loadProduct();JSON Module Import (Node.js v18+)
In modern Node.js versions (v18 and later) using ES Modules, JSON files can be imported directly with an assertion:
import data from "./data/student.json" assert { type: "json" };
console.log(data.name); // Output: Tejas KulkarniKey Points to Remember
require("file.json")is the simplest way to load a JSON file — Node.js parses it automaticallyfs.readFile()reads a JSON file asynchronously; useJSON.parse()on the resultfs.writeFile()saves a JSON string to a file; useJSON.stringify()first- Always use 2-space or 4-space indentation when saving JSON files for readability
- Use
try...catcharound file operations to handle missing files or invalid JSON package.jsonis the most common real-world example of a JSON configuration file in Node.js
Summary
Working with JSON files in Node.js is a fundamental backend skill. Whether reading configuration settings, loading seed data, or saving user records to a file, the pattern is always the same — use JSON.parse() when reading and JSON.stringify() when writing. Node.js makes this workflow straightforward with its built-in fs module and native support for JSON via require().
