Stu*_*emo 14 javascript node.js
我正在使用https.requestin node.js 请求远程文件.我对接收整个文件不感兴趣,我只想要第一个块中的内容.
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
});
});
Run Code Online (Sandbox Code Playgroud)
我想在第一个块之后完全停止接收响应,但是我没有看到任何关闭或结束方法,只是暂停和恢复.我使用暂停的担心是,对此响应的引用将无限期地挂起.
有任何想法吗?
rdr*_*rey 15
将其弹出一个文件并运行它.你可能需要调整到你的本地谷歌,如果你看到来自谷歌的301重定向答案(我相信,它作为单个块发送.)
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.
});
});
Run Code Online (Sandbox Code Playgroud)
要查看它res.destroy()确实有效,请取消注释,并且响应对象将继续发出事件,直到它自己关闭(此时节点将退出此脚本).
我也尝试了res.emit('end');而不是destroy(),但在我的一次测试运行中,它仍然发出了一些额外的块回调.destroy()似乎是一个更迫在眉睫的"终结".
destroy方法的文档在这里:http://nodejs.org/api/stream.html#stream_stream_destroy
但是你应该从这里开始阅读:http://nodejs.org/api/http.html#http_http_clientresponse(它声明响应对象实现了可读的流接口.)
| 归档时间: |
|
| 查看次数: |
10105 次 |
| 最近记录: |