I'm having some trouble with Node.js, and I think the problem might be that I am misunderstanding Node.js's approach to concurrency. Here is a stripped down example of the server I have written. The idea is that the server will be used for automated testing: it keeps a list of expected "configurations", and compares them to "configurations" that are sent by the client.
//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();
}
})
}
})
My understanding is that Node.js is single-threaded, so while it can spawn multiple tasks which can be handled asynchronously, only one thread of execution at a time will enter the JavaScript code running under Node.js. Unfortunately, the debugging output I am receiving from my server seems to defy this assumption:
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" ].
I read this as the following:
[ 'a' ]
[ 'a' ]
, as it did in step 2., it has the value ["c"]
.It seems I must be interpreting this incorrectly, because it defies my understanding of Node.js's single-threaded execution model, but right now I'm unable to see how else this can be interpreted. I'd appreciate any guidance anyone can offer on this.
try to repeat same test using console.error instead of console.log everywhere. As far as I know, console.log is non-blocking (data is buffered at the time of call and written to stdout at some point later) and console.error is blocking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With