Introduction
Appending to files lets you add new information to the end of an existing file without erasing what is already there.
Jump into concepts and practice - no test required
Appending to files lets you add new information to the end of an existing file without erasing what is already there.
import { appendFile } from 'node:fs/promises'; await appendFile('filename.txt', 'text to add\n');
import { appendFile } from 'node:fs/promises'; await appendFile('log.txt', 'New log entry\n');
import { appendFile } from 'node:fs/promises'; await appendFile('data.txt', 'More data here\n');
This program adds a reminder to 'notes.txt' and then reads and prints the whole file content to show the new text was added at the end.
import { appendFile, readFile } from 'node:fs/promises'; async function addNote() { const fileName = 'notes.txt'; await appendFile(fileName, 'Remember to drink water\n'); const content = await readFile(fileName, 'utf8'); console.log('File content after append:'); console.log(content); } addNote();
If the file does not exist, appendFile will create it automatically.
Use async/await or .then() to handle the promise returned by appendFile.
Remember to handle errors in real apps to avoid crashes.
Appending adds new text to the end of a file without deleting existing content.
Use 'appendFile' from 'fs/promises' for simple async file appending in Node.js.
Always consider adding a newline if you want each entry on its own line.
import { appendFile } from 'fs/promises';
await appendFile('log.txt', 'Entry1\n');
await appendFile('log.txt', 'Entry2');import fs from 'fs/promises';
fs.appendFile('data.txt', 'New line');
console.log('Appended');