create a file input.txt
1
|
Coding 4 Developers originated for sharing running codes with programmers. The journey was started on 14th January 2016. Coding for developers is not a tutorial website where you can learn step by step. It has running codes, you just can download or copy paste codes for your use.
|
create a file callback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
fs.readFile('input.txt',function(err, data){
if (err) return console.error(err);
console.log(data.toString());
});
console.log('Program ended before read file');
|
Output when blocking code:
Coding 4 Developers originated for sharing running codes with programmers. The journey was started on 14th January 2016. Coding for developers is not a tutorial website where you can learn step by step. It has running codes, you just can download or copy paste codes for your use.
Program Ended
Output when non-blocking code:
Program ended before read file
Coding 4 Developers originated for sharing running codes with programmers. The journey was started on 14th January 2016. Coding for developers is not a tutorial website where you can learn step by step. It has running codes, you just can download or copy paste codes for your use.
These two examples explain the concept of blocking and non-blocking calls.
- The first example shows that the program blocks until it reads the file and then only it proceeds to end the program.
- The second example shows that the program does not wait for file reading and proceeds to print "Program ended before read file" and at the same time, the program without blocking continues reading the file.