Node.js built-in fs module provides the fs.appendFile() method to asynchronously append data to a file. The file is automatically created if it doesn't already exist.

Here is an example that shows how you can use this method to append data to a file:

const fs = require('fs');

// append data to a file
fs.appendFile('file.txt', 'Hey there!', (err) => {
    if (err) {
        throw err;
    }
    console.log("File is updated.");
});

If you are appending text to a file that has a different encoding scheme than the default operating system encoding, you should pass the encoding scheme as the 3rd argument:

fs.appendFile('file.txt', 'Hey there!', 'utf8', (err) => { }

The fs module provides another method called fs.appendFileSync() to synchronously append text to a file. It blocks the Node.js event loop until the file append operation is finished. Here is an example:

const fs = require('fs');

// append data to a file
try {
    fs.appendFileSync('file.txt', "Hey there!");

    console.log("File is updated.");
} catch (error) {
    console.log(error);
}

Both fs.appendFile() and fs.appendFileSync() methods create a new file handle each time they are called. They are only good for a one-off append operation.

If you want to append repeatedly to the same file, for example writing in a log file, do not use these methods. Instead, you should use the fs.createWriteStream() method that creates a writable stream and reuses the file handle to append new data.

Here is an example:

const fs = require('fs');

// create a stream
const stream = fs.createWriteStream('file.txt', { flags: 'a' });

// append data to the file
[...Array(100)].forEach((num, index) => {
    stream.write(`${index}\n`);
});

// end stream
stream.end();

Check out how to read and write files in Node.js tutorial to learn more about handling files in a Node.js application.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.