File System Module:
The Node.js file system module allows you to work with the file system on your computer. It exports functions for working with files and directories. The fs module is responsible for all the asynchronous or synchronous file I/O operations.
To include the File System module, use the require() method:
we can perform read, write, delete and many more operations. Let us look at some of the most important operations.
Reading Files Synchronously and Asynchronously
The fs module provides simple methods to read files: fs.readFile() and fs.readFileSync(). The fs.readFile() is for reading file asynchronously and fs.readFileSync() is for reading files synchronously.
Here, file path has to be provided as a first argument and a callback function that will be called with file data.
For fs.readFileSync(), file path has to be provided as a first argument. utf8 is the default encoding, but we can specify any custom encoding that we need as the second parameter in both the methods.
Writing Files Synchronously and Asynchronously
Create a new file using the fs.writeFile() and fs.writeFileSync() method. The fs.writeFile() is for reading file asynchronously and fs.writeFileSync() is for reading files synchronously.
In the synchronous write operation
Deleting a File
To delete a file with the File System module, use the fs.unlink() method.
Renaming a File
A file can be renamed using fs.rename(). Here, it takes old file name, new file name and a callback function as arguments.