How to write to a file in Node.js
Short answer
writeFile() creates the file or completely replaces its content:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('greeting.txt', 'Hello, Anna!');
console.log(await readFile('greeting.txt', 'utf8'));Output:
Hello, Anna!An array of lines
Join the lines with a line break before writing:
import { readFile, writeFile } from 'node:fs/promises';
const tasks = ['Buy milk', 'Call Anna', 'Write a report'];
await writeFile('tasks.txt', tasks.join('\n') + '\n');
console.log(await readFile('tasks.txt', 'utf8'));Output:
Buy milk
Call Anna
Write a reportInto a folder that does not exist yet
writeFile() does not create folders. Create them first with mkdir() and the recursive option:
import { mkdir, writeFile, readFile } from 'node:fs/promises';
await mkdir('output/reports', { recursive: true });
await writeFile('output/reports/day.txt', 'done');
console.log(await readFile('output/reports/day.txt', 'utf8'));Output:
doneCommon mistake
Each writeFile() overwrites the file, so calling it in a loop leaves only the last line. To add to the end, use appendFile():
import { readFile, writeFile } from 'node:fs/promises';
for (const line of ['first', 'second', 'third']) {
await writeFile('log.txt', line + '\n');
}
console.log(await readFile('log.txt', 'utf8'));Output:
thirdFunctions used in this recipe
- Array.prototype.join — Joins array elements into a string.