3 Methods to Append to a File in Node.js (With Syntax & Examples)

In our file-handling journey, we encounter many scenarios where we would be required to append information to files in Node.js. Whether it may be to update a file or log new information onto an already existing file, appending is a must-know technique. In this article, we’ll look at a few methods by which we can append data to a file, but first, let’s understand how file handling works in Node.js.

File Handling in Node.js

File handling with Node.js involves operations like reading, writing, appending, and deleting data from files. To handle these operations Node.js provides a built-in fs (file system) module which can be installed using npm and imported to our file using require().

const fs = require('fs');

File handling operations can be performed synchronously, meaning only that a certain block of code is executed at a time, or asynchronously, meaning code execution is not blocked when a certain block of code is executed. Here, we’ll focus on some built-in asynchronous and synchronous functions provided by the fs module for appending data to a file.

Methods for Appending Data to a File in Node.js

Node.js provides various methods for appending to a file, some of them are as follows:

  • Using fs.appendFile()
  • Using fs.createWriteStream()
  • Using fs.appendFileSync()

1. Using fs.appendFile()

fs.appendFile() is a built-in function in the fs module which helps us append data to a file that already exists. Its syntax is as follows.

Syntax:

fs.appendFile(path, data, callback)

Parameters:

  • the path represents the absolute or relative path to the file where we will append data.
  • data is a string representing the data that will be appended to the file.
  • callback is an optional argument that calls a function after the operation is completed. It can be used to display a success message in the console if the operation is completed successfully or throw an error message if the operation is not successful.

Example:

Here, we have a file named file.txt which already contains some data.

File Before appendFile
File before append operation

Now we will append some data into the file using the appendFile() method

const fs = require('fs');

const filePath = 'file.txt';
const content = '\nNew data to append to the file using appendFile()';

fs.appendFile(filePath, content, (err) => {
  if (err) {
    console.error('Error:', err);
  } else {
    console.log('Data appended successfully.');
  }
});

Here, the filePath constant is used to store the path to our file (file.txt) as a string. The content constant stores the data we’ll append to the file, we add ‘\n’, a newline character to append the new data on the next line and not on the same line as the content already present in the file.

Then we call the appendFile() method and pass in the filePath and content as arguments. We pass in a callback function that represents an error object. This function is called when the append operation is completed and signifies whether the operation occurred successfully or didn’t.

Output:

Data Appended Using appendFile
Data appended to file.txt using appendFile()
Success Message Displayed After Appending
Message displayed on the terminal after data has been appended

2. Using fs.createWriteStream()

fs.createWriteStream() is an in-built function that creates a writeable stream in a file.

Syntax:

fs.createWriteStream(path, options)

Parameters:

  • path which is a string containing the absolute or relative path to the file we will be working with.
  • options contain the various options that can be given to the writeable stream. It usually holds strings or objects. Some of the options include flags, which are used to specify options like ‘a’ for append.

Example:

Let’s append some data into file.txt using the createWriteStream() method.

File Before createWriteStream
File before data has been appended to it

createWriteStream() can be used with the open event, which opens the file and allows you to append and then we can use it once more by listening to the finish event, which closes the file and displays a message depending on whether the append operation was successful.

const fs = require('fs');

const content = '\nNew data appended to the file using createWriteSteam()!';

const writeStream = fs.createWriteStream('file.txt', { flags: 'a' });
writeStream.on('open', () => {
  writeStream.write(content);
  writeStream.end();
});

writeStream.on('finish', (err) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log('Data appended successfully!');
});

Here, the ‘a’ flag is used as an option to indicate that the data stored in the content constant has to be appended. on() method of the writeStream() listens to the open or finish event which opens and closes the file (file.txt) respectively. write() writes the content onto the file when the file is opened and end() indicates all the content has been written.

When the finish event occurs, the file is closed and if the append was successful it displays a success message on the terminal, if it’s not, an error is thrown.

Appended Using createWriteStream
Data appended to file.txt using createWriteStream()

3. Using fs.appendFileSync()

This method is a synchronous file operation that can be used to append data to a file. It works similarly to the appendFile() method seen above except for the fact that it is synchronous while appendFile() is asynchronous. In this method, a new file is created if it doesn’t already exist.

Syntax:

fs.appendFileSync( path, data, options)

Parameters:

  • path represents the absolute/relative path to the file.
  • data represents the content to be appended to the file.
  • option contains options like flags like ‘a’ for append, encoding which has the default value ‘utf8’, and modes which is an integer value specifying a file mode.

Example:

File Before appendFileSync
File before data has been appended to it

In this example, we’ll use appendFileSync() in a try-catch block to append data to file.txt which displays a success message in the try block if the data is appended successfully. The catch block throws an error if data has not been appended.

const fs = require('fs');

const data = '\nNew data to append to the file using appendFileSync()';

try {
  fs.appendFileSync('file.txt', data);
  console.log('Data appended successfully!');
} catch (err) {
  console.error(err);
}

Output:

Data Appended Using appendFileSync
Data appended to file.txt using appendFileSync()

Conclusion

Appending data to a file allows us to easily add and update the contents of a file without overwriting its original contents. Here we explored three methods provided by the fs module for appending data, fs.appendFile(), fs.createWriteStream(), and fs.appendFileSync(). These methods allow us to append data synchronously and asynchronously depending on our need. Mastering various append functions will help us seamlessly work with files.

Reference

https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node

Nandana Pradosh
Nandana Pradosh
Articles: 27