How to read a file in Node.js
Short answer
readFile() from the node:fs/promises module reads the whole file. Pass the encoding 'utf8' to get a string:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('notes.txt', 'Buy milk\nCall Anna');
const text = await readFile('notes.txt', 'utf8');
console.log(text);Output:
Buy milk
Call AnnaA missing file
If there is no file, readFile() throws an error with the code ENOENT:
import { readFile } from 'node:fs/promises';
try {
await readFile('missing.txt', 'utf8');
} catch (error) {
console.log(error.code);
}Output:
ENOENTSynchronous reading
In small scripts, readFileSync() from node:fs is simpler: it returns the content right away:
import { readFileSync, writeFileSync } from 'node:fs';
writeFileSync('version.txt', '1.4.2');
console.log(readFileSync('version.txt', 'utf8'));Output:
1.4.2Common mistake
Without the encoding you get a Buffer, raw bytes, instead of a string:
import { readFileSync, writeFileSync } from 'node:fs';
writeFileSync('hello.txt', 'Hi');
console.log(readFileSync('hello.txt'));
console.log(readFileSync('hello.txt', 'utf8'));Output:
<Buffer 48 69>
HiFunctions used in this recipe
- JSON.parse — Parses a JSON string and returns the value.