How to Append to a File in Node?

Better Stack Team
Updated on April 4, 2024

In Node.js, you can append data to a file using the fs (File System) module. The fs.appendFile function is specifically designed for this purpose. Here's an example:

 
const fs = require('fs');

const filePath = 'path/to/your/file.txt'; // Replace with the actual path to your file
const dataToAppend = 'New data to append\\n';

// Append data to the file
fs.appendFile(filePath, dataToAppend, (err) => {
  if (err) {
    console.error('Error appending to file:', err);
    return;
  }

  console.log('Data appended to file successfully.');
});

In this example:

  1. Replace 'path/to/your/file.txt' with the actual path to the file you want to append data to.
  2. dataToAppend is the content you want to add to the file.
  3. The fs.appendFile function takes three arguments:
    • The file path.
    • The data to append.
    • A callback function that is called once the operation is complete. If there's an error, it will be passed to the callback.

This method is suitable for appending relatively small amounts of data. If you're working with larger datasets or need more control over the writing process, consider using fs.createWriteStream for streaming data to a file.

 
const fs = require('fs');

const filePath = 'path/to/your/file.txt'; // Replace with the actual path to your file
const dataToAppend = 'New data to append\\n';

// Create a write stream and append data
const writeStream = fs.createWriteStream(filePath, { flags: 'a' });

writeStream.write(dataToAppend, (err) => {
  if (err) {
    console.error('Error appending to file:', err);
    return;
  }

  console.log('Data appended to file successfully.');
  writeStream.end();
});

Using fs.createWriteStream is more efficient for handling large datasets or situations where you need more control over the writing process. Adjust the approach based on your specific use case and requirements.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github