Node.js调试跟踪似乎意味着多个执行线程 - 如何正确解释这个?

jbe*_*rd4 5 concurrency node.js

我在使用Node.js时遇到了一些麻烦,我认为问题可能是我误解了Node.js的并发方法.这是我编写的服务器的精简示例.这个想法是服务器将用于自动化测试:它保留一个预期的"配置"列表,并将它们与客户端发送的"配置"进行比较.


//expectedConfigurations gets initialized up here

var server = http.createServer(function(request, response) {
    switch (url.pathname) {
        case "/check-configuration":
            jsonData = "";
            request.on("data", function(data) {
                return jsonData += data;
            });

            request.on("end", function() {
                var configuration, errMsg, expectedConfiguration;

                console.log("finished reading json data", jsonData);
                expectedConfiguration = expectedConfigurations.shift();
                console.log("Expected configuration", expectedConfiguration);
                configuration = new Set(JSON.parse(jsonData));
                if (expectedConfiguration.equals(configuration)) {
                    response.writeHead(200, {"Content-Type": "text/plain"});
                    response.write("Matched expected configuration.");
                    return response.end();
                } else {
                    response.writeHead(500, {
                        "Content-Type": "text/plain"
                        });
                    errMsg = "Did not match expected configuration. Received: " + (JSON.stringify(configuration)) + ". Expected:" + (JSON.stringify(expectedConfiguration)) + ".";
                    response.write(errMsg);
                    response.end();
                    console.error(errMsg);
                    results.testsFailed.push(currentTest);
                    return transitionToBeforeSendingTestState();
                }

            })
    }
})
Run Code Online (Sandbox Code Playgroud)

我的理解是Node.js是单线程的,因此虽然它可以产生可以异步处理的多个任务,但是一次只有一个执行线程将进入在Node.js下运行的JavaScript代码.不幸的是,我从服务器收到的调试输出似乎无视这个假设:


received request for /check-configuration
finished reading json data [ "a" ]
Expected configuration [ "a" ]
received request for /check-configuration
Did not match expected configuration. Received: [ "a" ]. Expected: [ "c" ].
Run Code Online (Sandbox Code Playgroud)

我读这个如下:

  1. 服务器接收请求.它开始异步读取请求数据.
  2. 服务器完成读取请求数据,通过移动它来改变expectedConfigurations,并将结果分配给expectedConfiguration [ 'a' ]
  3. 然后线程被服务器的新请求打断!这就是我对Node.js下单线程执行JavaScript内容的期望似乎打破了.
  4. 最后,恢复与第一个请求相关的原始执行线程.将预期的配置与接收的实际配置进行比较,但现在,不是[ 'a' ]像在步骤2中那样具有该值,而是具有该值["c"].

似乎我必须正确地解释这个,因为它违背了我对Node.js的单线程执行模型的理解,但是现在我无法看到如何解释这个问题.我很感激任何人都可以提供任何指导.

And*_*rov 1

尝试在各处使用 console.error 而不是 console.log 重复相同的测试。据我所知,console.log 是非阻塞的(数据在调用时缓冲并在稍后的某个时刻写入标准输出),而 console.error 是阻塞的。