File handling in Node.js
The most important functionalities provided by programming languages are Reading and Writing files from the computers. Node.js provides the functionality to read and write files from the computer. Reading and Writing the file in Node.js is done by using one of the coolest Node.js modules called fs module, it is one of the most well-known built-in Node.js modules out there.
Synchronous method to read the file: To read the file in synchronous mode we use a method in fs module which is readFileSync(). It takes two parameters first is the file name with complete path and the second parameter is the character encoding which is generally ‘utf-8’.
Synchronous method to writing into a file: To write the file in a synchronous mode we use a method in fs module which is writeFileSync(). It takes two parameters first is the file name with the complete path in which content is to be written and the second parameter is the data to be written in the file.
Asynchronous method to read and write from/into a file: To read/write the file in an asynchronous mode in fs module we use readFile() and writeFile() methods. The fs.readFile() takes three parameters first is the file name with the complete path, the second parameter takes the character encoding which is generally ‘utf-8’ and the third parameter is the callback function (which is fired after reading complete file) with two parameters, one is the error in case error occurred while reading file and second is the data that we retrieve after reading the file and the fs.writeFile() also takes three parameters, file name with its complete path, the second parameter is the data to be written in file and the third is a callback function which fires in case an error occurs while writing file.
Note: An Asynchronous method first completes the task (reading the file) and then fires the callback function.
If we talk in terms of Promise the asynchronous file handling method in Node.js, we have to use promisify method which takes a function following the callback approach as an input and returns a version of this function which returns a promise. The code looks like as shown below (async-await approach has been followed here.) :
Let’s have a look at the terminal to figure out whether the code worked or not.
So, this is another way to achieve the same result as far as asynchronous file-handling in Node.js is concerned.