What is appendfile() function?

We can also use the fs module to append the content using appendFile function into a file. However, appendFile function will create the file if the file doesn’t exist or append the content into the file, if the file already existed.

Let’s create a folder structure similar to below referenced image.

(Figure1: Folder structure)

So let’s see how can we achieve the similar folder structure, firstly create a file colors.json inside the assets folder with the given below data or you can make a JSON file according to you.

colors.json

{
  "sample": true,
  "name": "color list",
  "description": "A list of colors",
  "colorList": [
    {
      "color": "red",
      "hex": "#FF0000"
    },
    {
      "color": "green",
      "hex": "#00FF00"
    },
    {
      "color": "blue",
      "hex": "#0000FF"
    }
  ]
}

Now Let’s create a file namely append.js

append.js

const fs = require("fs");
const colorData = require("./assets/colors.json");

colorData.colorList.forEach((c) => {
  fs.appendFile("./storage-files/color.md", `${c.hex} \n`, (err) => {
    if (err) {
      throw err;
    }
  });
});

Let’s run the file into the terminal as you can see into the below output screenshot.

using the command node <file-name>

(Figure 2: Output)

And when we do so it look like nothing happens but when you actually go to the storage-files folder you will notice that there is now a new file created in storage-files folder called color.md.

( Figure 3: Folder structure after appending)

Please take note here that color.md file was not previously existed it is created when we have run the command to execute the file. So appendFile() create the file in which we try to append the content if the file doesn’t already exist.

Now again run the append.js file into the terminal multiple time. As the color.md was already created above, so each time we execute the command it will append the content into the existing file instead of creating file for each and every instance. Please observe the result in the color.md file you will see lots of line added.

( Figure 4: output file after lots of append)

Please visit official site for more information at https://nodejs.org/api/fs.html#filehandleappendfiledata-options

Hurray! Thank you for sticking till the last and all your support. Hope I have able to delivered a great stuff 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *