I-am-batman
I-am-batman

Reputation: 187

Why does the control flow does not follow the code execution order?

I was trying out the following example in nodejs

"use strict";

const 
  fs = require('fs');

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

})

fs.writeFile('target.txt','writing some content',function(err){
  if(err)
    throw err;
console.log("file saved")
})

As per the code, I read the file, print its content. Then I write some content in the same file and print the text file saved in the console. But my output is

file saved
writing some content

The writeFile function is executed first rather than the readFile. Why does this happen and how can this be avoided?

Upvotes: 2

Views: 114

Answers (1)

the6p4c
the6p4c

Reputation: 664

The functions you pass as the second argument to those two functions are callbacks. They are executed when the operation is completed - and execution order is not guaranteed.

To guarantee that the write occurrs after the read is complete, place the code to trigger a write into the callback of the readFile method.

"use strict";

const fs = require('fs');

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

    fs.writeFile('target.txt', 'writing some content', function(err) {
        if(err) throw err;
        console.log("file saved")
    });
});

Upvotes: 5

Related Questions