3
fs.readFile('input.txt', function(err, data) {
  if (err) {
    return console.error(err);
  }
  console.log(data.toString());
});

console.log("Program Ended");

input.txt contains the string "hello".

The above code prints:
Program Ended
hello

Why does it print "program ended" before "hello"?
Is it not line by line execution?

Community
  • 1
  • 1
Shah Rukh K
  • 559
  • 1
  • 5
  • 19

2 Answers2

2

Code inside your callback function (the one which prints the file content) does not block execution. It is executed asynchronously after the file is read.

madox2
  • 49,493
  • 17
  • 99
  • 99
0

fs.readFile is asynchronous, meaning that, as @madox2 said, it will not block execution. If you want to log Program Ended after fs.readFile, you can use fs.readFileSync. fs.readFileSync is synchronous, meaning that console.log("Program Ended") will be executed after.

CrazyVideoGamer
  • 754
  • 8
  • 22