0
0
Node.jsframework~5 mins

Appending to files in Node.js

Choose your learning style9 modes available
Introduction

Appending to files lets you add new information to the end of an existing file without erasing what is already there.

Saving new chat messages to a log file without losing old messages.
Adding new entries to a daily report file as events happen.
Recording user actions or errors continuously in a log file.
Keeping track of sensor data by adding new readings to a file.
Updating a list of tasks by adding new tasks at the end.
Syntax
Node.js
import { appendFile } from 'node:fs/promises';

await appendFile('filename.txt', 'text to add\n');
Use the 'appendFile' function from the 'fs/promises' module for easy async file appending.
Always add a newline '\n' if you want each appended text on a new line.
Examples
This adds 'New log entry' to the end of 'log.txt'.
Node.js
import { appendFile } from 'node:fs/promises';

await appendFile('log.txt', 'New log entry\n');
This appends 'More data here' to 'data.txt'.
Node.js
import { appendFile } from 'node:fs/promises';

await appendFile('data.txt', 'More data here\n');
Sample Program

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.

Node.js
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();
OutputSuccess
Important Notes

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.

Summary

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.