We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

JavaScript is a popular programming language that lets you handle files in the surfing app.

The environment NodeJS is used for different scripts which include file handling.

NodeJS is nothing but an environment to run JavaScript code.

I hope you have a basic understanding of NodeJS.

Lets jump into the tutorial to learn about file handling in JavaScript.

So, NodeJS provides a module calledfs (file system)for file handling.

Lets see different methods from thefsmodule.

fs.open()

The methodfs.open()will take two argumentspathandmode.

Thepathis used to locate the file.

The argumentmodeis used to bring up the file in different modes likeappending, writing,andreading.

Lets see the list of modes and corresponding operations.

If the file doesnt exist on the given path, then it will create a new empty file.

Lets see the code for opening a file in different modes.

The methodfs.open()will throw an error if the file doesnt exist while opening inreadingmode.

It will create a new empty file inwritingandappendingmodes.

We can perform different operations on the opened file.

If the file doesnt exist in the given path, then it will create a new one.

Append some content to the file using the below code.

fs.writeFile()

The methodfs.writeFile()is used to write the content to the file.

If the file doesnt exist in the given path, then it will create a new one.

Try the below code for writing the content to a file.

fs.readFile()

The methodfs.readFile()is used to read the content from a file.

It will throw an error if the file doesnt exist in the given path.

Examine the following code for the method.

The methodfs.unlink()is used to delete the file.

It will throw an error if the file doesnt exist in the given path.

Have a look at the code.

fs.rename()

The methodfs.rename()is used to rename the file.

It will throw an error if the file doesnt exist in the given path.

Rename the next file with the following code.

Now, you are familiar with different file handling methods from thefs (file system)module.

Conclusion

Thats it for this tutorial.

you could use the file handling methods to automate some of the boring stuff in your day-to-day tasks.

I hope you have learned the essential methods for handling files.