Synchronous File IO

1. Introduction to Synchronous File IO

If you are not using node.js event based call back, it will be a simple synchronous(blocking) IO.

Example

Let us see and example of blocking File IO.

/*
Sync file io.
*/


var fs = require('fs');
var data = fs.readFileSync("myText.txt");

console.log (data.toString());

console.log ("Program Ended");

Here we have mentioned require(‘fs’) to use a module fs in the current code of javascript. This is possible because of modules object in node.js.

fs.readFileSync("myText.txt");

The above statement reads the file myText.txt in synchronous mode. The information fetched from the file is stored in data variable.

console.log (data.toString());

In the above line data is converted to string and then printed on console.

The contents of myText.txt are:

 

Hello world
This is Parth

Hello world
This is Parth

Hello world
This is Parth

 

Execute the program:

 

D:\work\nodejs> node iotest1.js

Hello world
This is Parth

Hello world
This is Parth

Hello world
This is Parth

Program Ended

 

You can observe from the above output that “Program Ended” was printed at the end. This means the program waited till the time the file was read and then executed the last line of code. This is because of synchronous mode of IO.