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)
我读这个如下:
[ 'a' ][ 'a' ]像在步骤2中那样具有该值,而是具有该值["c"].似乎我必须正确地解释这个,因为它违背了我对Node.js的单线程执行模型的理解,但是现在我无法看到如何解释这个问题.我很感激任何人都可以提供任何指导.
尝试在各处使用 console.error 而不是 console.log 重复相同的测试。据我所知,console.log 是非阻塞的(数据在调用时缓冲并在稍后的某个时刻写入标准输出),而 console.error 是阻塞的。