Appending to Files in Node.js

Appending Files Featured Image

In this article, we’ll learn about appending to files in Nodejs. Lately, we have been talking a lot about files and their reading and writing and whatnot. Well, I am back with yet another Nodejs tutorial for you, this time on appending/adding changes to your files.

The fs or the file system module does a lot, so you can expect more tutorials coming in based on the topic.

Generally, updating something means a lot more than what we call it in programming. On a general note, update refers to deleting, creating, replacing, adding changes and the list goes on.

Well, when programming with Node.js in specific, the meaning of update crumbles down to appending, prepending, or replacing changes to a file or directory.

Today, I will be discussing a little about the fs.append file().

Also read: Writing Files in Node.js

Getting Started with Appending to Files

We can append changes to our file easily with the fs.appendFile() method. This will asynchronously append changes/or contents to a file. If the file doesn’t exist, it is created.

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

You can use parameters or arguments to change the behavior of this method.

Below listed, are some of them:

  • 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

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’.

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.

Using fs.appendFile()

DISCLAIMER: We will be using the fs.readFileSync() method in the below code snippets. If that means nothing to you, click here to read about reading files in Node.js.

Let us first start with a simple example by including our fs core module:

const fs = require('fs');

Now, let’s create a new file and add some text to it: 

// Grabs the file contents before the append operation
console.log("\nYour file before you appended:",
  fs.readFileSync("party_stuff_list.txt", "utf8"));
 
// Appending to file
fs.appendFile("party_stuff_list.txt", "Confetti", (err) => {
  if (err) {
    console.log(err);
  }
  else {
    // Grabs the file contents after the append operation
    console.log("\nYour file after you appended:",
      fs.readFileSync("party_stuff_list.txt", "utf8"));
  }
});

Here’s the result:

Your file before you appended: Balloons

Your file after you appended: BalloonsConfetti

Let us move forward to a second example where we will use the optional parameters.

// Grabs the file contents before the append operation
console.log("\nYour file before you appended:",
  fs.readFileSync("shopping_list.txt", "utf8"));
   
// Appending to file
fs.appendFile("shopping_list.txt", " – Gummy Bears",
  { encoding: "latin1", mode: 0o666, flag: "a" },
  (err) => {
    if (err) {
      console.log(err);
    }
    else {
      // Grabs the file contents after the append operation
      console.log("\nYour file after you appended:",
        fs.readFileSync("shopping_list.txt", "utf8"));
    }
  });

Here’s the result:

Your file before you appended: Your favorite candy

Your file after you appended: Your favorite candy – Gummy Bears

Conclusion

The fs.appendFile() can help developers easily append changes to files. You can use parameters or arguments to change the behavior of this method.

Notable References