在获取大量图像下载的同时在Node.js http.get中包含超时
这是我一直用来从url下载图片的代码:
http.get(options, function (res) { res.on('data', function (data) { file.write(data); }).on('end', function () { file.end(); console.log(file_name + ' downloaded '); cb(null, file.path); }).on('error', function (err) { console.log("Got error: " + err.message); cb(err, null); }); });
如何为每个请求添加一个超时,以便它不会一直等待大数据或无响应的响应?
好的,你的问题至less有两个解决scheme。 简单的一个:
var request = http.get(options, function (res) { // other code goes here }); request.setTimeout( 10000, function( ) { // handle timeout here });
但可能不够灵活。 更高级的一个:
var timeout_wrapper = function( req ) { return function( ) { // do some logging, cleaning, etc. depending on req req.abort( ); }; }; var request = http.get(options, function (res) { res.on('data', function (data) { file.write(data); // reset timeout clearTimeout( timeout ); timeout = setTimeout( fn, 10000 ); }).on('end', function () { // clear timeout clearTimeout( timeout ); file.end(); console.log(file_name + ' downloaded '); cb(null, file.path); }).on('error', function (err) { // clear timeout clearTimeout( timeout ); console.log("Got error: " + err.message); cb(err, null); }); }); // generate timeout handler var fn = timeout_wrapper( request ); // set initial timeout var timeout = setTimeout( fn, 10000 );
- 使用NodeJS从url下载大文件时,服务器崩溃
- 使用$ routeProvider是否节省networking带宽?
- 在使用AngularJS发送GET请求时,无法从WebStorm IDE执行“打开”无效URL
- org.springframework.web.multipart.MultipartException:无法parsing多部分servlet请求…stream意外结束
- `server.listen()`如何保持节点程序运行
- ECONNREFUSED错误,在其他客户端不会出现node.js错误
- KOA中的POST请求未定义请求主体
- Express.js在控制器中获取http方法
- 用Node.js /强大的中止用户请求