The short answer

#

Import the functions from node:fs/promises and await them. Pass an encoding such as 'utf8' when you want a string back instead of a Buffer.


_10
import { readFile, writeFile } from 'node:fs/promises';
_10
_10
const text = await readFile('notes.txt', 'utf8');
_10
await writeFile('notes-copy.txt', text);

Why it happens

#

Node's fs module has three styles of the same functions:

  • Callback, such as fs.readFile(path, callback), the original API.
  • Sync, such as fs.readFileSync(path), which blocks the whole process until the disk responds.
  • Promise, from node:fs/promises, which returns promises you can await.

The promise API is the one to reach for in modern code. It works with async and await, it does not block other requests while the disk is busy, and errors become normal exceptions you can catch with try and catch. The sync versions are still fine for short scripts and start-up code, where blocking does not matter.

One thing catches people out: relative paths are resolved from the current working directory, which is wherever the process was started, not from the file that contains the code.

How to fix it

#

Build paths from the current file

Use import.meta.dirname in ES modules, or __dirname in CommonJS, so the path works no matter where you run the script from.


_10
import { readFile } from 'node:fs/promises';
_10
import path from 'node:path';
_10
_10
const configPath = path.join(import.meta.dirname, 'config.json');
_10
const config = JSON.parse(await readFile(configPath, 'utf8'));

Write, append and create folders

writeFile replaces the file, creating it if needed. appendFile adds to the end. Neither creates missing folders, so call mkdir with recursive: true first.


_10
import { mkdir, writeFile, appendFile } from 'node:fs/promises';
_10
_10
await mkdir('output/reports', { recursive: true });
_10
_10
await writeFile(
_10
'output/reports/summary.json',
_10
JSON.stringify({ total: 42 }, null, 2),
_10
);
_10
_10
await appendFile('output/log.txt', `Finished at ${new Date().toISOString()}\n`);

Handle missing files

If the file does not exist, the promise rejects with an error whose code is 'ENOENT'. Check for it rather than testing for the file first, which can race with other processes.


_12
import { readFile } from 'node:fs/promises';
_12
_12
async function readJson(file, fallback) {
_12
try {
_12
return JSON.parse(await readFile(file, 'utf8'));
_12
} catch (error) {
_12
if (error.code === 'ENOENT') return fallback;
_12
throw error;
_12
}
_12
}
_12
_12
const settings = await readJson('settings.json', {});

List, inspect and delete


_12
import { readdir, stat, rm } from 'node:fs/promises';
_12
_12
const entries = await readdir('output', { withFileTypes: true });
_12
_12
for (const entry of entries) {
_12
if (entry.isFile()) {
_12
const info = await stat(`output/${entry.name}`);
_12
console.log(entry.name, info.size);
_12
}
_12
}
_12
_12
await rm('output/tmp', { recursive: true, force: true });

Stream large files

readFile loads the whole file into memory. For large logs or CSV files, read it line by line with a stream instead.


_10
import { open } from 'node:fs/promises';
_10
_10
const file = await open('big.log');
_10
_10
for await (const line of file.readLines()) {
_10
if (line.includes('ERROR')) console.log(line);
_10
}

Write safely

If the process crashes halfway through writeFile, you can be left with a half-written file. For important data, write to a temporary file and rename it, which replaces the original in one step on the same drive.


_10
import { writeFile, rename } from 'node:fs/promises';
_10
_10
await writeFile('data.json.tmp', JSON.stringify(data));
_10
await rename('data.json.tmp', 'data.json');

Common pitfalls

#
  • Forgetting 'utf8' and getting a Buffer, which prints as a list of bytes.
  • Forgetting await, so the code carries on before the file is written.
  • Running many writes to the same file in parallel with Promise.all. The order is not guaranteed; write in sequence or collect the data first.
  • Using existsSync before reading. Just read and handle ENOENT.
  • Reading huge files with readFile and running out of memory. Stream them.
#
file under:
Node.js

quick question

Was this resource helpful?