node.jsevent-loop

Node's queues: order of Check Queue vs IO Queue?


If I understand correctly, in Node, in terms of priority, IO Queue > Check Queue.

But if you run this code:

fs.readFile('./tweets.json', (err, data) => {
  console.log('IO Queue');
});
setImmediate(() => {
  console.log('Check Queue');
});

The result is:

Check Queue
IO Queue

Moreover, if there's an error, the result logs are reversed. Is there something else involved I'm not aware of?


Solution

  • The callback passed to readFile is only queued when the either the file is read or an error occurs. In the case the file is read, this takes some time on the non-JS level, so when node monitors its queues it finds that the IO queue is still empty and goes on with the check queue.

    Depending on the error, it might be that the error condition is immediate, like a badly constructed file name. In that case the callback will be placed in the IO queue immediately, and node will find it first.