Node.js:如何停止stream式传输数据

我使用请求npm模块创build一个请求。 但是,如果内容types不是json,我希望stream停止。 目前,它不会停止,并产生错误,因为解压缩读取一个无效的头.. 我们如何能够停止一个stream?

var req = request(options) req .on('error', function (err) { console.log("err"); reject(err) }) .on('response', function(response) { if(response.headers['content-type'] != 'application/json') { console.log(response.headers['content-type']) req.destroy() // doesn't work this.destroy() // doesn't work } }) .on('end', function () { resolve() }) .pipe(gunzip) // ERROR! 

你可以使用stream.pause() ,如下所示:

 var req = request(options) req .on('error', function (err) { console.log("err"); reject(err) }) .on('response', function(response) { if(response.headers['content-type'] != 'application/json') { console.log(response.headers['content-type']) req.pause(); // stream paused reject('not json'); } }) .on('end', function () { resolve() }) .pipe(gunzip)