Asynchronous File IO

1.Introduction to Asynchronous File IO

In this example we will see how can we read a file in Asynchronous fashion. Node.js has an event loop model. Event loop models are those who want an event to trigger a callback function as well as relinquishing the CPU cycles for the other task while there is no event callback in the queue.

I/O in such Asynchronous File IO will be non-blocking and you may observe that the thread will not wait for the complete read operation, rather execute other lines of code followed by it, until the call back of read operation is fired.

Example:

See the following code for Asynchronous File Read:

var fs = require('fs');


fs.readFile('myText.txt',function(err,data){
  if (err){
    console.log(err);
  }
  console.log(data.toString());
  
});


console.log("End of program");

The signature of readFile is:

fs.readFile(file[, options], callback)

Here, we are not using any options in the preceding example. First argument is the name of file to be read. There are optional options which can be passed as parameters. Callback function is triggered when the read operation is done with.

Two arguments of callback are err and data. If there is any error in the read operation, the err will not be undefined. In the above example we have printed the data by converting it to string by using a toString() function.

data.toString()

The contents of the file myText.txt is as follows:

Hello world
This is Parth

Hello world
This is Parth

Hello world
This is Parth

Hello world
This is Parth

After executing it prints output:

d:\work\nodejs> node iotest2.js
End of program
Hello world
This is Parth

Hello world
This is Parth

Hello world
This is Parth

Hello world
This is Parth

Here we can see that “End of program” is printed in beginning itself. This because, while event loop was waiting for calling callback for readFile, node executed rest of the statements in the code.

This example is not only a sample for file read mechanism but also gives an insight of event loop model in nodejs architecture.