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.
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.
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);
}2 lines
ENOENTThe 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).