Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 report

Into 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:

done

Common 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:

third

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.