Skip to content

Instantly share code, notes, and snippets.

@strager
Created January 25, 2012 07:56
Show Gist options
  • Save strager/1675280 to your computer and use it in GitHub Desktop.
Save strager/1675280 to your computer and use it in GitHub Desktop.
// Why does this code sample hang client
// connections if ASYNC === true?
//
// # Start server
// node test.js --sync port
// node test.js --async port
//
// # Test
// curl http://host:port/
var ASYNC = true;
var PORT = 8022;
var http = require('http');
var i = 2;
// --sync, --async flag
switch (process.argv[i]) {
case '--async':
ASYNC = true;
++i;
break;
case '--sync':
ASYNC = false;
++i;
break;
default:
break;
}
// Port number
if (!isNaN(process.argv[i])) {
PORT = Number(process.argv[i]);
++i;
}
http.createServer(function (req, res) {
console.log("Request received");
req.on('end', function () {
console.log("'end' received");
});
req.pause();
function respond() {
req.on('end', function () {
// This is not called if ASYNC === true
console.log("'end' received (test passed)");
res.writeHead(200);
res.end();
});
req.resume();
}
if (ASYNC) {
process.nextTick(respond);
} else {
respond();
}
}).listen(PORT);
console.log(
"%s-responding HTTP server listening on :%d",
ASYNC ? "Asynchronously" : "Synchronously",
PORT
);
@strager
Copy link
Author

strager commented Jan 26, 2012

To test:

curl http://localhost:8022/

curl should return almost instantaneously.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment