How to Read JSON File in Node.js: Simple Guide
In Node.js, you can read a JSON file using the
fs module's readFileSync or readFile methods, then parse the content with JSON.parse(). Alternatively, you can use import with assert { type: 'json' } in modern Node.js versions for direct JSON import.Syntax
To read a JSON file in Node.js, you typically use the fs module to read the file content as a string, then convert it to a JavaScript object using JSON.parse().
fs.readFileSync(path, encoding): Reads file synchronously.fs.readFile(path, encoding, callback): Reads file asynchronously.JSON.parse(string): Converts JSON string to object.
javascript
const fs = require('fs'); // Synchronous read const data = fs.readFileSync('file.json', 'utf-8'); const obj = JSON.parse(data); // Asynchronous read fs.readFile('file.json', 'utf-8', (err, data) => { if (err) throw err; const obj = JSON.parse(data); console.log(obj); });
Example
This example shows how to read a JSON file named data.json asynchronously and log its content as a JavaScript object.
javascript
import { readFile } from 'fs/promises'; async function readJson() { try { const data = await readFile('data.json', 'utf-8'); const obj = JSON.parse(data); console.log(obj); } catch (error) { console.error('Error reading JSON file:', error); } } readJson();
Output
{ "name": "Alice", "age": 30 }
Common Pitfalls
Common mistakes when reading JSON files in Node.js include:
- Forgetting to specify the encoding (like
'utf-8'), which causes the data to be a buffer, not a string. - Not handling errors from file reading or JSON parsing, which can crash your program.
- Using synchronous reading in performance-critical or server environments, which blocks the event loop.
javascript
const fs = require('fs'); // Wrong: missing encoding, data is a buffer const data = fs.readFileSync('file.json'); const obj = JSON.parse(data.toString()); // Fixed: convert buffer to string // Right: specify encoding to get string const dataCorrect = fs.readFileSync('file.json', 'utf-8'); const objCorrect = JSON.parse(dataCorrect);
Quick Reference
Tips for reading JSON files in Node.js:
- Use
fs/promiseswithasync/awaitfor clean asynchronous code. - Always specify
'utf-8'encoding to get a string. - Wrap
JSON.parse()in try-catch to handle invalid JSON. - For small config files, synchronous reading is okay during startup.
- In Node.js 18+, you can import JSON files directly using
import data from './file.json' assert { type: 'json' }.
Key Takeaways
Use the fs module to read JSON files and JSON.parse() to convert to objects.
Always specify 'utf-8' encoding to read file content as a string.
Prefer asynchronous reading with async/await for non-blocking code.
Handle errors from file reading and JSON parsing to avoid crashes.
In modern Node.js, you can import JSON files directly with import assertions.