Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何提前结束node.js http请求_Javascript_Node.js - Fatal编程技术网

Javascript 如何提前结束node.js http请求

Javascript 如何提前结束node.js http请求,javascript,node.js,Javascript,Node.js,我正在使用node.js中的https.request请求远程文件。我对接收整个文件不感兴趣,我只想要第一块中的内容 var req = https.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (d) { console.log(d); res.pause(); // I want this to end instead

我正在使用node.js中的
https.request
请求远程文件。我对接收整个文件不感兴趣,我只想要第一块中的内容

var req = https.request(options, function (res) {
    res.setEncoding('utf8');

    res.on('data', function (d) {
         console.log(d);
         res.pause(); // I want this to end instead of pausing
    });
});
我想在第一个块之后完全停止接收响应,但我没有看到任何关闭或结束方法,只有暂停和恢复。使用“暂停”时,我担心的是,对该响应的引用将无限期地挂起


有什么想法吗?

将其放入文件并运行。如果你看到来自谷歌的301重定向回复(我相信它是作为一个块发送的),你可能必须适应你当地的谷歌

若要查看
res.destroy()
是否真正起作用,请取消对其注释,响应对象将一直发出事件,直到它自己关闭为止(此时节点将退出此脚本)

我还试验了
res.emit('end')
而不是
destroy()
,但在我的一次测试运行期间,它仍然触发了一些额外的块回调
destroy()
似乎是一个更加迫在眉睫的“终结”

销毁方式的单据如下:


但是您应该从这里开始阅读:(它说明响应对象实现了可读流接口。)

这里称为
范围<代码>范围:字节=0-1023
仅下载第一个KiBi,例如。顺便说一句,是不是有
res.end()
?遗憾的是,res.end()在回调函数中不存在。似乎不再存在。是否有一个状态键,我们可以检查请求是否被销毁?res.destroy()的问题表示将发出
结束
事件,无法区分已完成下载和已取消下载。
var http = require('http');

var req = http.get("http://www.google.co.za/", function(res) {
  res.setEncoding();
  res.on('data', function(chunk) {
    console.log(chunk.length);
    res.destroy(); //After one run, uncomment this.
  });
});