1

Even though I get no errors and I'm able to print the file data, the input_1 does not seem to change to true in the whole loop. I therefore don't print 'y', just an endless series of x. I want the while loop to wait until the input_1 variable changes and I don't want to use promises.

var fs = require("fs");
var input_1 = false;
var input_2 = false;

fs.readFile('input.txt', function(err, data){

    if (err) {return console.log(err);};
    console.log(data.toString());
    input_1 = true;

})

fs.readFile('input2.txt', function(err, data){
    if (err) {return console.log(err);};
    console.log(data.toString());
    input_2 = true;

})

while(!input_1){
    console.log('x')
}

console.log('y')
  • 3
    JavaScript is single-threaded. If you make an infinite loop, nothing else will ever happen. – 4castle Feb 18 '17 at 01:26
  • readFile is an asynchronous function. you either need to change your code to support this fact, or change to readFileSync – Przemek Lewandowski Feb 18 '17 at 01:41
  • The idea is that the two read file operations remain asynchronous and when the the first file is read successfully, the value of input_1 will change to true. When it does, the while loop should exit. Why isn't it doing so? If I do a setTimeout instead of a while loop and check the value of input_1, it's updated to true. – user3308138 Feb 18 '17 at 01:45

1 Answers1

0

I could be wrong in this situation but what it looks like to me at the moment is a asynchronous issue. I'm not totally familiar with the readFile function in nodeJS but what you may need to do is chain a promise from the file readers or on their callback.

The underlying issue I believe is that the while loop is run before the callback is changing the values of the variables in which you have been testing.

  • yes but shouldn't the while loop detect the change in input_1 after the callback gets executed upon success and input_1 's value changes to true? – user3308138 Feb 18 '17 at 02:03