The Quick Way: readFileSync + JSON.parse
For a config file or a script, read the file as text and parse it:
{
"name": "Emily",
"port": 3000,
"features": ["auth", "logs"]
}const fs = require('node:fs')
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'))
console.log(config.name, config.port) // Emily 3000Always pass 'utf8'. Without it, readFileSync returns a Buffer; JSON.parse turns it into a string for you, but stating the encoding makes the code clear and avoids surprises with other encodings.
Without Blocking: fs/promises
In a server or any async code, use the promise version so other requests are not held up:
import { readFile } from 'node:fs/promises'
const text = await readFile(new URL('./config.json', import.meta.url), 'utf8')
const config = JSON.parse(text)
console.log(config.features.join(', ')) // auth, logsIn CommonJS, use const { readFile } = require('node:fs/promises') inside an async function.
require() and import
const config = require('./config.json')import config from './config.json' with { type: 'json' }Both are short, and both read the file only once. Node caches the result, so every later require returns the same object: if one part of your code changes it, everyone sees the change. We set port = 9999 on the object from require, and the next require('./config.json') also returned 9999. Changes to the file on disk are not picked up until the process restarts. Use readFileSync or readFile when the file can change while the app runs, such as a data file you also write to.
The with { type: 'json' } part is required for JSON imports in current Node versions. Older guides show assert { type: 'json' }, the earlier spelling.
Write a JSON File
const fs = require('node:fs')
const config = { name: 'Emily', port: 8080, features: ['auth', 'logs'] }
fs.writeFileSync('config.json', JSON.stringify(config, null, 2) + '\n'){
"name": "Emily",
"port": 8080,
"features": [
"auth",
"logs"
]
}JSON.stringify(value, null, 2) indents with two spaces so the file stays easy to read and to compare in Git. The final '\n' ends the file with a newline, which most editors and linters expect. In async code, use await writeFile(...) from node:fs/promises the same way.
Error: ENOENT, no such file or directory
A relative path like 'config.json' is resolved from the folder you run node in, not the folder the script is in. Running the same script from its parent folder gave ENOENT. Build the path from the script's own location:
const path = require('node:path')
const file = path.join(__dirname, 'config.json')
const config = JSON.parse(fs.readFileSync(file, 'utf8'))const file = new URL('./config.json', import.meta.url)
const config = JSON.parse(readFileSync(file, 'utf8'))require('./config.json') and import already resolve paths from the script's folder, which is one reason they seem to "just work".
Error: Unexpected token at the Very Start (the BOM)
If a file that looks perfect fails with an error pointing at the first character, it probably starts with an invisible byte order mark (BOM, U+FEFF). Some Windows editors add it when saving as "UTF-8 with BOM". This is the error Node 24 gave us for {"name": "Emily"} saved with a BOM:
SyntaxError: Unexpected token '', "{"name": "Emily"}" is not valid JSONThe quoted character looks empty because it is invisible. Remove it before parsing:
const text = fs.readFileSync('config.json', 'utf8').replace(/^\uFEFF/, '')
const config = JSON.parse(text)Interestingly, require() strips the BOM itself, so the same file loaded with require worked. To fix the file for good, re-save it as plain "UTF-8" in your editor (in VS Code, click the encoding in the status bar).
Error: Expected double-quoted property name
That message, or any other SyntaxError from JSON.parse, means the file is not valid JSON. For {"name": "Emily",} Node reported Expected double-quoted property name in JSON at position 17 (line 1 column 18): a trailing comma. Catch the error so your app can explain what went wrong:
function loadJson(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'))
} catch (err) {
if (err.code === 'ENOENT') throw new Error(`${file} not found`)
throw new Error(`${file} is not valid JSON: ${err.message}`)
}
}Paste the file into the JSON Validator to see the exact line, or let JSON Repair fix trailing commas, single quotes and comments for you.
Large Files: Read Line by Line
JSON.parse needs the whole file in memory. For logs and exports with millions of records, store one JSON object per line (JSON Lines) and read it as a stream:
import { createReadStream } from 'node:fs'
import { createInterface } from 'node:readline'
let errors = 0
const rl = createInterface({ input: createReadStream('logs.jsonl'), crlfDelay: Infinity })
for await (const line of rl) {
if (!line.trim()) continue
if (JSON.parse(line).level === 'error') errors++
}
console.log('errors:', errors)Which Method Should You Use?
| Situation | Use |
|---|---|
| Small script, CLI tool, config at startup | readFileSync + JSON.parse, or require / import |
| Web server, file read while handling requests | fs/promises readFile |
| File that changes while the app runs | readFile each time, never require |
| Very large data | JSON Lines and readline |
Saving data back with JSON.stringify? If an object refers to itself, see Converting Circular Structure to JSON. If a file is empty or was cut off while writing, reading it fails with Unexpected End of JSON Input.
Frequently Asked Questions
How do I read a JSON file in Node.js?
Read it as text and parse it: JSON.parse(fs.readFileSync('data.json', 'utf8')). In async code use readFile from node:fs/promises. require('./data.json') and import data from './data.json' with { type: 'json' } also work, but they read the file only once.
How do I write JSON to a file in Node.js?
Turn the object into text with JSON.stringify(data, null, 2) and save it with fs.writeFileSync('data.json', text) or await writeFile from node:fs/promises. The 2 indents the file so it is easy to read.
Why do I get ENOENT when the file exists?
A relative path is resolved from the folder you run node in, not the folder of the script. Build the path with path.join(__dirname, 'data.json') in CommonJS or new URL('./data.json', import.meta.url) in ES modules.
Why does JSON.parse fail on the first character of a valid-looking file?
The file probably starts with an invisible byte order mark (BOM) added by some Windows editors. Remove it with text.replace(/^/, '') before parsing, or re-save the file as UTF-8 without BOM.