Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to append to a file in Node.js

Short answer

appendFile() adds text to the end of the file and creates the file if it does not exist:

import { appendFile, readFile } from 'node:fs/promises';
 
await appendFile('visits.txt', 'Anna\n');
await appendFile('visits.txt', 'Oleg\n');
 
console.log(await readFile('visits.txt', 'utf8'));

Output:

Anna
Oleg

A simple log

Add the time and the message to each line:

import { appendFile, readFile } from 'node:fs/promises';
 
const log = (message) => appendFile('app.log', `${new Date().toISOString()} ${message}\n`);
 
await log('Server started');
await log('User logged in');
 
const lines = (await readFile('app.log', 'utf8')).trim().split('\n');
console.log(lines.length, lines[1].endsWith('User logged in'));

Output:

2 true

Many writes

For frequent writes, open a stream once instead of opening the file every time:

import { createWriteStream } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { once } from 'node:events';
 
const stream = createWriteStream('numbers.txt', { flags: 'a' });
for (let i = 1; i <= 3; i++) stream.write(`line ${i}\n`);
stream.end();
await once(stream, 'finish');
 
console.log(await readFile('numbers.txt', 'utf8'));

Output:

line 1
line 2
line 3

Common mistake

appendFile() does not add a line break by itself. Without \n the lines stick together:

import { appendFile, readFile } from 'node:fs/promises';
 
await appendFile('names.txt', 'Anna');
await appendFile('names.txt', 'Oleg');
 
console.log(await readFile('names.txt', 'utf8'));

Output:

AnnaOleg

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.