gpt4 book ai didi

node.js - express 是否解决了 "blocking code"问题?

转载 作者:搜寻专家 更新时间:2023-11-01 00:18:50 24 4
gpt4 key购买 nike

我正在从 Node Beginner Book 学习 node.js以及随后的电子书购买。在书中,Manuel Kiessling 解释了一行像这样的阻塞代码:

fs.readFileSync(blah);

将阻止整个 Node 进程和所有进入的请求。这对于多用户网站来说非常糟糕!

这是 Kiessling 使用的示例:

exec("ls -lah", function( error, stdout, stderr ) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stdout);
response.end();
});

这是欺骗我的代码。他说 ls -lah 可以很容易地替换为更耗时的操作,例如 find/-name "*" 或数据库查找。由于异步回调,我假设昂贵且阻塞的操作会以某种方式显式地在后台运行。

所以我必须用这段代码来检验我的理论:

var http = require("http");
var url = require("url");

badSleep = function(ms) {
var now = new Date();
var finishAtDate = now.getTime() + ms;
console.log("CPU burning sleep for " + ms + " milliseconds");
while(new Date() < finishAtDate) {
// do nothing
}
};

asyncWrapper = function(callback) {
//badSleep(3000);
callback();
}

http.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Serve up " + pathname);
if (pathname == '/favicon.ico') {
response.writeHead(404);
response.end();
} else {
asyncWrapper(function() {
badSleep(3000);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("\nI was wrong " + new Date());
response.end();
});
}
}).listen(8888);

问题是,无论我把 sleep 放在哪里,它仍然阻塞 Node 事件循环。回调不会解决阻塞问题。 SO 的优秀用户也在评论中告诉我这一点。

那么exec是怎么做到的呢???我感到莫名其妙,所以我去看了child-process code at github .我发现 exec 调用了 spawn!!!它使一个子进程!谜团已揭开。异步代码不能“解决”阻塞问题,spawn 可以。

这引出了我的问题。 express 是否以某种方式解决了阻塞问题,还是您仍然需要担心?

PS:本题重写。我想向下面的 SO 用户道歉,并感谢他们对我的耐心等待。我肯定在这里学到了一些东西。

最佳答案

Someone posted a comment about understanding-the-node-js-event-loop. Yes exactly. You can issue a blocking call if you wrap it in an asynchronous call, because you are not blocking the node event loop.

如果您用异步调用包装同步调用,您仍然会遇到阻塞。例如,如果你这样写:

fs.readFile("file1.txt", function(err, data1) {
var data2 = fs.readFileSync("file2.txt");
});

进程在读取 file1.txt 时不会被阻塞,因为您使用的是异步调用,但是,一旦完成读取 file1 并到达读取 file2 的行 ,它就会阻塞

通过在异步/非阻塞调用中发出同步/阻塞调用,您只是延迟阻塞。

您是正确的,对整个网站进行阻塞确实很糟糕,这就是为什么您不应该非常频繁地发出阻塞调用的原因。由于 node.js 是从头开始编写的,因此默认情况下大多数 I/O 调用都是异步的,您应该尽可能多地使用它们而不是同步调用。

The question is, does express handle this for you automatically or do you still have to worry about it?

你还是要担心。

关于node.js - express 是否解决了 "blocking code"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15877364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com