Node.jsdebugging跟踪似乎意味着多个线程的执行 – 如何正确解释这个?

我在Node.js上遇到一些麻烦,我想这个问题可能是我误解了Node.js的并发方法。 这里是我写的服务器的一个简单的例子。 这个想法是,服务器将用于自动化testing:它保留一个预期的“configuration”列表,并将它们与客户端发送的“configuration”进行比较。

//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是单线程的,所以虽然它可以产生多个可以asynchronous处理的任务,但是一次只能执行一个执行线程,而不会进入在Node.js下运行的JavaScript代码。 不幸的是,我从我的服务器收到的debugging输出似乎违背了这个假设:

 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" ]. 

我读这个如下:

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

看来我必须正确地解释这个,因为它无法理解我对Node.js的单线程执行模型的理解,但是现在我看不到这个怎么解释。 我会很感激任何人都可以提供这方面的指导。

尝试使用console.error而不是console.log来重复相同的testing。 据我所知,console.log是非阻塞的(数据在调用时被caching,稍后在某个时间写入标准输出),而console.error被阻塞。