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.
_10import { readFile, writeFile } from 'node:fs/promises';_10_10const text = await readFile('notes.txt', 'utf8');_10await 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 canawait.
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.
_10import { readFile } from 'node:fs/promises';_10import path from 'node:path';_10_10const configPath = path.join(import.meta.dirname, 'config.json');_10const 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.
_10import { mkdir, writeFile, appendFile } from 'node:fs/promises';_10_10await mkdir('output/reports', { recursive: true });_10_10await writeFile(_10 'output/reports/summary.json',_10 JSON.stringify({ total: 42 }, null, 2),_10);_10_10await 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.
_12import { readFile } from 'node:fs/promises';_12_12async 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_12const settings = await readJson('settings.json', {});
List, inspect and delete
_12import { readdir, stat, rm } from 'node:fs/promises';_12_12const entries = await readdir('output', { withFileTypes: true });_12_12for (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_12await 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.
_10import { open } from 'node:fs/promises';_10_10const file = await open('big.log');_10_10for 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.
_10import { writeFile, rename } from 'node:fs/promises';_10_10await writeFile('data.json.tmp', JSON.stringify(data));_10await 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
existsSyncbefore reading. Just read and handleENOENT. - Reading huge files with
readFileand running out of memory. Stream them.
Related reading
#Node.jsquick question
Was this resource helpful?