• NodeJs http.get 方法请求时间过长问题处理!


    NodeJs 获取网页内容 http.get 默认请求超时过长了,程序要卡死好一会。

    根据网上资料现改造了一个带超时设置的获取网页内容方法。

    主要方法使用 setTimeout 来超时,

    代码如下:

    // 获取指定网页,返回HTML
    function getUrlHtml(url, fn_success, fn_error, timeout)
    {
        timeout = timeout || 2000;
        var timeEvent;
        var req = http.get(url, function(res){
            var html = '';
            res.setEncoding('utf-8');
            res.on('data' , function(d){
                window.clearTimeout(timeEvent);
                html += d; 
            }).on('end', function(){
                window.clearTimeout(timeEvent);
                //var dom = jq(html);
                return fn_success(html);
            }).on('error', function(err){
                window.clearTimeout(timeEvent);
                fn_error(err);
            });
        }).on('error', function(err){
            window.clearTimeout(timeEvent);
            fn_error(err);
        });
        
        timeEvent = window.setTimeout(function(){
            fn_error('time out!');
            req.abort();
        }, timeout);
    }
    
    // 使用
    getUrlHtml('http://www.xxx.com', function(html){
        console.log(html);
    }, function(err){
        console.log(err);
    }, 1000);
  • 相关阅读:
    超级迷宫我的计划表
    不敢死队
    Let the Balloon Rise
    Hangover
    汉诺塔系列2
    Tri Tiling(递推)
    Tiling(递推,高精度)
    Color Me Less
    I Think I Need a Houseboat(圆计算)
    Kbased Numbers(递推)
  • 原文地址:https://www.cnblogs.com/zjfree/p/4788495.html
Copyright © 2020-2023  润新知