我有以下请求处理程序,我认为它们应该是非阻塞的,但事实并非如此。如果我发送上传请求,即使它正在运行 child_process,它也会阻止其他请求。我做错了什么?
var exec = require("child_process").exec;
function upload(response) {
console.log(new Date().toISOString() + ": Request handler 'upload' was called.");
exec("echo 'Hello Upload'", function (error, stdout, stderr) {
function sleep(milliSeconds) {
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
sleep(10000);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stdout);
response.end();
console.log(new Date().toISOString() + ":" + stdout);
});
console.log(new Date().toISOString() + ": Request 'upload' dispatched.");
}
这是日志:
2014-03-03T18:19:33.615Z: Request handler 'upload' was called.
2014-03-03T18:19:33.631Z: Request 'upload' dispatched.
2014-03-03T18:19:43.641Z:'Hello Upload'
谢谢
最佳答案
您正在回调中休眠,而不是子进程中;
exec("echo 'Hello Upload'", function (error, stdout, stderr) {
...
sleep(10000);
...只会在子进程中运行 echo 'Hello Upload'
,当 echo 完成时,它将终止进程并回调到事件线程上的 sleep 状态。这将阻塞事件循环并导致整个程序阻塞。
关于node.js - 为什么这个请求处理函数会阻止其他请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154326/