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.
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");
The above statement reads the file myText.txt in synchronous mode. The information fetched from the file is stored in data variable.
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.