node.js - 获取请求后,脚本不会返回到控制台 [英] node.js - after get request, script does not return to console

查看:129
本文介绍了node.js - 获取请求后,脚本不会返回到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的脚本

    var http = require("http");

    http.get( WEBSITE, function(res) {
       console.log("Does not return");
       return;
    });

如果 WEBSITE 变量是' http://google.com '或' http ://facebook.com '脚本不会返回控制台。
但如果 WEBSITE 变量为' http://yahoo.com '或' http://wikipedia.org '它返回到控制台。有什么不同?

if WEBSITE variable is 'http://google.com' or 'http://facebook.com' script does not return to console. but if WEBSITE variable is 'http://yahoo.com' or 'http://wikipedia.org' it returns to console. What is the difference?

推荐答案

通过返回控制台我假设您的意思是退出并退回到shell提示符下。

By "return to console" I'm assuming you mean that node exits and drops you back at a shell prompt.

事实上,节点最终退出您列出的所有域名。 (你只是不耐烦。)

In fact, node does eventually exit for all of those domains you listed. (You were just impatient.)

你看到的是HTTP保持活动的结果。默认情况下,节点在HTTP请求完成后保持TCP连接打开。这使得对同一服务器的后续请求更快。只要TCP连接仍然打开,节点就不会退出。

What you are seeing is the result of HTTP keep-alives. By default, node keeps the TCP connection open after a HTTP request completes. This makes subsequent requests to the same server faster. As long as a TCP connection is still open, node will not exit.

最终,节点或服务器将关闭空闲连接(因此节点将退出)。谷歌和Facebook可能允许空闲连接比雅虎和维基百科更长时间存在。

Eventually, either node or the server will close the idle connection (and thus node will exit). It's likely that Google and Facebook allow idle connections to live for longer amounts of time than Yahoo and Wikipedia.

如果您希望脚本发出请求并尽快退出完成后,您需要禁用HTTP keep-alives。您可以通过禁用代理商支持来执行此操作。

If you want your script to make a request and exit as soon as it completes, you need to disable HTTP keep-alives. You can do this by disabling Agent support.

http.get({ host:'google.com', port:80, path:'/', agent:false }, function(res) {
   ...
});

如果您需要此特定功能,则仅禁用代理。在正常,长期运行的应用中,禁用代理可能会导致许多问题。

Only disable the Agent if you need this specific functionality. In a normal, long-running app, disabling the Agent can cause many problems.

还有您可以采取其他一些方法来避免保持节点运行

这篇关于node.js - 获取请求后,脚本不会返回到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆