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
OlegA 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 trueMany 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 3Common 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:
AnnaOlegFunctions used in this recipe
- Date.prototype.toISOString — Returns the date in ISO 8601 format in UTC.