Node.js readline线事件callback保证在下次调用之前完成?

我刚刚修复了一个错误,我正在读取并用readline重写文件,并且这些行被乱序写入(最终是由于asynchronousfs.write()调用)。

但是有一件事我以为发生了,就是readline 行事件是按照正确的顺序进来的,但是也许我的一些行的callback函数在另一个line事件被处理之后就完成了。

展示:

 line1 event comes in line1 event finishes handling line2 event comes in //Takes a long time to process line3 event comes in line3 event finishes handling line2 event finished handling //And because it was after line3, gets written back after too 

从上面输出的最终文件将如下所示:

 line1 line3 line2 

我没有看到任何这样的保证文件,我的testing似乎指出,以上是不可能的,但我不知道。 readline是否可以实现上面的场景?

NodeJS在单个事件循环上运行JavaScript代码,JavaScript规范称之为作业队列 。 这意味着,当你的代码正在运行对line2的响应时,保证它在运行时不会被调用来响应line3 – 如果在你的代码运行的时候发生了这个事件,那么调用你的callback的作业是排队等待的,作业队列,直到完成,事件循环可以选取队列中的下一个作业。

显然,这只对同步代码才是正确的,因为asynchronous的东西(如fs.write )只启动一个进程,他们不会等待它完成; 完成是添加到队列中的作业。 因此,asynchronous调用的callback可能会在下一个事件进入后发生。

例如,考虑这个代码:

 stream.on("line", function() { // do a lot of synchronous work that may tie up the thread for a while }); 

你可以确定你的callback不会被第3行调用,而它仍然在处理第2行的callback。

但在处理第2行的callback时:

 stream.on("line", function() { // Code here IS guaranteed to run before we get called for line 3 callAnAsyncFunction(function(err, data) { // Code here is NOT guaranteed to run before we get called for line 3 }); // Code here IS guaranteed to run before we get called for line 3 });