Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 Anna

A 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:

ENOENT

Synchronous 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.2

Common 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>
Hi

Functions used in this recipe

  • JSON.parse — Parses a JSON string and returns the value.

Thanks for reading!

Donate to the site — we work hard for you.