Frameworks Knowledge Base

Working with JSON in Node.js: File, Fetch & Streams

Complete Node.js JSON guide: reading/writing JSON files with fs.readFileSync, streaming large JSON with JSONStream, and type-safe parsing with Zod.

In Node.js, use fs.readFileSync() with JSON.parse() to read JSON files, or require() to import JSON directly. For API responses, use fetch (Node 18+) and call response.json() to parse the result.

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.
json
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) });
});

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

How do I read a JSON file in Node.js?

Use JSON.parse(fs.readFileSync("file.json", "utf8")) or the async equivalent with fs.promises.readFile().

How do I write JSON to a file in Node.js?

Use fs.writeFileSync("output.json", JSON.stringify(data, null, 2)) for sync or the async fs.promises.writeFile() version.

How do I parse JSON request bodies in Express?

Add app.use(express.json()) middleware to your Express app to automatically parse JSON request bodies.

Related JSON Topics & Reference Articles