nodejs中的模块请求不会停止pipe道

我已经使用dicer来parsingpipe道的请求,但我不知道哪个停止pipe道的命令。

dicer.on('part', function(part) { var frameEncoded = ''; part.setEncoding('base64'); part.on('header', function(header) { }); part.on('data', function(data) { frameEncoded += data; }); part.on('end', function() { console.log(frameEncoded); }); }); var options = { method: 'GET', uri: 'http://192.168.1.2/video.mjpeg/' } request(options).pipe(dicer) //only for test setTimeout(function() { console.log('stop request.pipe'); var options = { method: 'GET', uri: 'http://192.168.1.2/video.mjpeg/' } request(options).end() //<-- ?? which command?? This not work... }, 5000); 

uri指向一个ipcamerastream,不可能抓取事件连接closures的请求,因为stream是无限的。

访问请求底层套接字的一种方法是侦听请求对象上的socket事件。 那么这只是closures该套接字的问题。 例如:

 var req = request(options); req.on('socket', function(sock) { setTimeout(function() { console.log('stop request.pipe'); sock.end(); // or sock.destroy(); }, 5000); }); req.pipe(dicer); 

请注意,发送socket事件时请求可能尚未启动。 socket事件基本上让你知道一个套接字已被分配用于请求(这是特别有用的,当你使用的HTTP代理,其maxSockets设置为一个有限的价值,所以你可能不一定会得到一个套接字马上分配)。

你也可以尝试:

 var req = request(options); req.on('response', function(res) { setTimeout(function() { console.log('stop request.pipe'); res.socket.end(); // or res.socket.destroy(); }, 5000); }); req.pipe(dicer); 

@ mscdex的方法适用于我。 这是代码: –

  request("https://www.linkedin.com/afhdjalsdjhdks") .on("error", function (error) { process.stderr.write(error.code) }) .on("response", function (resp) { if ((resp.statusCode !== 200) && (resp.statusCode !== 201)) { process.stderr.write(format("%s - %s", resp.statusCode, resp.statusMessage)) resp.socket.destroy() } }) // .pipe(StreamAll()) .pipe(process.stdout)