Synchronous vs Asynchronous
Every method in the fs module has synchronous as well as asynchronous forms. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. It is better to use an asynchronous method instead of a synchronous method, as the former never blocks a program during its execution, whereas the second one does.
Example
Create a text file named input.txt with the following content −
Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!!
Let us create a js file named main.js with the following code −
var fs = require("fs"); // Asynchronous read fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); // Synchronous read var data = fs.readFileSync('input.txt'); console.log("Synchronous read: " + data.toString()); console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Synchronous read: Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Program Ended Asynchronous read: Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!!
The following sections in this chapter provide a set of good examples on major File I/O methods.
Open a File
Syntax
Following is the syntax of the method to open a file in asynchronous mode −
fs.open(path, flags[, mode], callback)
Parameters
Here is the description of the parameters used −
- path − This is the string having file name including path.
- flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below.
- mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.
- callback − This is the callback function which gets two arguments (err, fd).