How to Append Data to a File with node.js



node.js

In this article, we show how to append data to a file with node.js.

Let's say that you have a file somewhere on your computer system. This may be a blank file or may be a file that already has contents in it.

You can append more content, or data, to this file using the fs.appendFileSync() function to append data.

If the file does not exist, then the fs.appendFileSync() function will create the file and then write the contents to it that you specify.

So let's now show in code how to append to a file with node.js

The existing file that we will write to is a file named, 'Me.txt'. The file currently has the contents, 'My name is David'.

We will append to this file, " I currently live in New York"



So the first thing we must do is import the fs module. This we do using the require() function. We set this equal to the const, fs, which allows us to use the fs module. The fs module stands for file system.

We then use the fs.appendFileSync() to append to a file.

The first parameter that the fs.appendFileSync() takes is the name of the file. If the file you are appending to is not in the current working directory, then you must specify the full path to this file.

The second parameter is the text that you want to append to the file. In this case, it is, "I current live in New York"

There is an optional third parameter, if you want to specify the encoding of the file. You can specify something such as 'utf-8'.

After running this script, you should now open the text file and see the appended text in the file.

Again, if the file never existed in the directory for which you are running your script, then it will be created. It will not run an error if the file doesn't exist. So if you are running this script, make sure that you spell the full path way correctly. If you're off, then this could unintentionally create a new file that you didn't intend to create.

And this is how to append to a file with node.js.


Related Resources

How to Find the Version of node.js Installed on Your Computer



HTML Comment Box is loading comments...