对Node.js的单线程执行模型感到非常困惑



好吧,我正在学习Node.js,但我无法将注意力集中在这个等待模型上。我是通过阅读节点入门书来学习的。其中有一节是关于阻塞和非阻塞操作的。我不明白的是非阻塞操作。

这是代码:

var exec = require("child_process").exec;
function start(response) {
  console.log("Request handler 'start' was called.");
  exec("ls -lah", function (error, stdout, stderr) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(stdout);
    response.end();
  });
}
function upload(response) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello Upload");
  response.end();
}
exports.start = start;
exports.upload = upload;

启动函数名为exec,exec执行ls-lah。那么回调将等待响应,对吗?如果exec执行"find/",在我的计算机中,大约需要30秒才能完成"find/"命令。由于这是单线程的,如果用户1访问启动函数,那么在几毫秒内,用户2也访问启动函数。然后会发生什么?这是否意味着用户1将在30秒内得到响应,而用户2将需要等待1分钟,因为用户1仍在执行"查找/"?

如果我的问题太无聊,我很抱歉。感谢阅读!

在node.js中,所有I/O操作都是异步工作的。两个find操作将并行运行。请阅读以下内容:了解node.js事件循环。

最新更新