Skip to content
jshacks.dev
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read
Summarize in AI

fs.promises.readFile returns a promise, so you can await it without callbacks. Pass an encoding, or you get a Buffer and not a string.

JavaScript
import { readFile, writeFile } from 'node:fs/promises';

await writeFile('notes.txt', 'first line\nsecond line\n');

const text = await readFile('notes.txt', 'utf8');
console.log(text.split('\n').length - 1, 'lines');

try {
  await readFile('missing.txt', 'utf8');
} catch (error) {
  console.log(error.code);
}
Text
2 lines
ENOENT

The second argument 'utf8' decodes the bytes. A missing file rejects with an error whose code is ENOENT, which you can check to tell "not found" from a permission error such as EACCES.

readFile loads the whole file into memory, so use createReadStream for large files. Relative paths resolve against the process's working directory, not the script's, so build paths from import.meta.dirname when the file sits next to your code. The module is [node:fs/promises](https://nodejs.org/api/fs.html#promises-api).

Also inAsync
Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.