JSON in Node.js
Node.js handles JSON natively through JSON.parse()/JSON.stringify() and the fs module for file operations.
Reading JSON Files
require('./data.json')— Synchronous, cached, simple.JSON.parse(fs.readFileSync('data.json', 'utf8'))— Synchronous, non-cached read.JSON.parse(await fs.promises.readFile('data.json', 'utf8'))— Async/await pattern.
import fs from 'node:fs';
import { readFile } from 'node:fs/promises';
// Read JSON synchronously
const data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));
// Read JSON asynchronously
const jsonText = await readFile('./data.json', 'utf8');
const parsed = JSON.parse(jsonText);
// Write JSON to file
fs.writeFileSync('./output.json', JSON.stringify(data, null, 2));
// Fetch JSON from API (Node 18+ native fetch)
const res = await fetch('https://api.example.com/users');
const users = await res.json();
// Express.js — Parse JSON request bodies
import express from 'express';
const app = express();
app.use(express.json()); // Built-in JSON body parser
app.post('/api/data', (req, res) => {
const body = req.body; // Already parsed JSON
res.json({ received: true, keys: Object.keys(body) });
});