当请求超时时,nodejs http.request关闭进程

时间:2018-01-23 11:13:29

标签: node.js https error-handling

const request = https.request(options, (response) => {})
request.on('socket', (socket) => {
    socket.setTimeout(100)
    socket.on('timeout', () => {
        console.log(`timeout`.red);
        request.abort()
    })
})
request.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
});

错误和杀死进程。 需要在没有杀死进程的情况下记录错误

1 个答案:

答案 0 :(得分:0)

我不相信超时会导致您的进程退出。尝试使用与您的代码非常相似的代码,您可以将超时设置为您想要故意导致此错误的任何内容。我已经稍微修改了你的代码以等待用户输入,然后退出。

const https = require ('https');

const options = {
    hostname: "httpbin.org",
    path: "/ip"
}

var request = https.request(options,  (res) => {
    console.log('statusCode:', res.statusCode);
    res.on('data', (d) => {
        process.stdout.write(d);
    });

});

request.on('socket', (socket) => {
    socket.setTimeout(1000);
    socket.on('timeout', () => {
        console.log(`timeout`.red);
        request.abort()
    })
})

request.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
});

request.end();

var stdin = process.openStdin();

console.log('Press <enter> to exit..');

stdin.addListener("data", function(d) {
    console.log('exiting..');
    process.exit(1);
});