Appending Contents to a File in Node.js: A Guide to Using the fs.appendFile() Method

In Node.js we can interact with files using the File System module, known as the FS module. The FS module is a built-in module that comes with Node having methods that can be used to read files, write to files, delete files and also update the files.

To update a file, we can use the FS writeFile() method, which replaces the current contents of the file with the data we pass in. The problem with this method is that we lose the data contained in the file.

If we want to update without losing the existing file data then we can use the FS module method appendFile() which can be used to append data while preserving the existing content in the file. It appends new data to the end of the file.

In this tutorial, we will learn to use that method to append the given data to the file.

Append to File in Node.js using fs.appendFile() Method

The fs.appendFile() method asynchronously appends data to a file. If the file in the specified file path does not exist, it will create a new file instead of giving an error.

Syntax:

fs.appendFile(path, data[, options], callback)

Where,

  • path – String, Buffer, URL or Number. Denotes source filename, or file descriptor to be appended to.
  • data – String, or Buffer. Denotes data to be appended.
  • options – String or Object. Used to specify optional parameters that will affect the output. Optional parameters include:
    • encoding – String, default = utf8.
    • mode – Integer. Specifies the file mode, default = ‘0o666’.
    • flag – String, default = ‘a’.
  • callback – (optional function (error) {}) if no error is present, then err === null, otherwise err will be the error message

More on encoding

File encoding refers to the character sets used by the contents of a file. As mentioned above, ‘utf8’ encoding is very common and hence set as default too.

UTF-8 encoding is commonly for web pages and most documents. Other most common encodings are ‘ascii’, ‘binary’, ‘hex’, ‘base64’, and ‘utf16le’.

More on flags

You may use flags according to your requirements such as for appending or prepending content:

  • r+ – opens the file for reading and writing. An error occurs if the file doesn’t exist.
  • w+ – opens the file for reading and prepending the content at the beginning of the file. Creates the file if it does not exist.
  • a – opens the file for appending the content at the end of the file. Creates the file if it does not exist.
  • a+ – opens the file for reading and appending the content at the end of the file. Creates the file if it does not exist.

Find more flags here on the official documentation of Node.js.

Example of using fs.appendFile() Method

Let’s see some code examples of appending data to a file using fs.appendFile() Method.

Example 1:

For this example, we have an existing file named sample.txt having data: “Hello World”.

const fs = require('fs');

const filePath = './sample.txt';
const newData = ' New contents...';

fs.appendFile(filePath, newData, (err) => {
  if (err) {
    console.error(err);
  } else {
    const fileData = fs.readFileSync(filePath, 'utf8');
    console.log('File contents:', fileData);
  }
});

Here we have passed an error object to the callback function(last argument) to check for the error. If an error occurs, it will throw in the console, or else we have used readFileSync() method that will read the content after appending and print it in the console.

Output:

File contents: Hello World New contents...

In the above output, we can see that the data has been appended successfully.

Example 2:

For this example, we will try to append data to a file asynchronously that does not exist.

const fs = require('fs');

const filePath = './nonexistentfile.txt';
const newData = 'Hello World\n';

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

The file “nonexistent file.txt” does not exist.

Output:

Data appended successfully 🎉

See, we didn’t get any error, which means that the file with the specified data has been created successfully.

Conclusion

In this tutorial, we have seen that NodeJS has a module FS which is used to interact with the file system. This module has a method fs.appendFile() which can be used to append data to a file. This method takes a path, data and an options object as an argument, additional using callbacks we can check for error to handle it when it occurs. Hope this tuitorial helps you to understand the method to append data to a file using Node.js.

References

Aneesha S
Aneesha S
Articles: 172