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

Concurrency Node.js调试跟踪似乎意味着执行多个线程-如何正确解释这一点?,concurrency,node.js,Concurrency,Node.js,我在Node.js上遇到了一些问题,我认为问题可能是我误解了Node.js的并发方法。下面是我编写的服务器的一个精简示例。其想法是,服务器将用于自动化测试:它保留一个预期“配置”列表,并将它们与客户端发送的“配置”进行比较 //expectedConfigurations gets initialized up here var server = http.createServer(function(request, response) { switch (url.pathname)

我在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();
                }

            })
    }
})
我的理解是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" ].
我的理解如下:

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

  • 看来我一定是错误地解释了这一点,因为这违背了我对Node.js单线程执行模型的理解,但现在我看不出还有什么其他解释。我非常感谢任何人对此提供的指导。

    尝试使用console.error而不是console.log到处重复相同的测试。 据我所知,console.log是非阻塞的(数据在调用时缓冲,稍后写入stdout),console.error是阻塞的