高地中的请求流未正确传递

时间:2014-02-22 12:11:01

标签: node.js stream highland.js

我在使用nodejs request流时遇到问题,因为我传递映射它已经是空的数组。

var _       = require('highland'),
    fs      = require('fs'),
    request = require('request');

// This works but not using the stream approach
// function get(path) {

//     return _(function (push, next) {

//         request(path, function (error, response, body) {
//             // The response itself also contains the body
//             push(error, response);
//             push(null, _.nil);
//         });
//     });
// }

var google = _(request.get('http://www.google.com'));

google
// res is empty array
.map(function (res) {
    // console.log(res);
    return res;
})
// res is empty array
.toArray(function (res) {

    console.log(res);
});

1 个答案:

答案 0 :(得分:5)

request()模块使用一种旧式流 - 它从代码Stream模块调用流原型上的.pipe()方法:

stream.Stream.prototype.pipe.call(this, dest, opts)

https://github.com/mikeal/request/blob/11224dd1f02e311afcc11df8a8f0be1d9fb2bf83/request.js#L1310

我将实际问题追溯到以下检查节点的核心流模块:

function ondata(chunk) {
  if (dest.writable) {
    if (false === dest.write(chunk) && source.pause) {
      source.pause();
    }
  }
}

https://github.com/joyent/node/blob/master/lib/stream.js#L50

可以通过在上面的示例中执行以下操作来修补此问题

var google = _(request.get('http://www.google.com'));
google.writable = true;

我提出了一个拉取请求,以便在https://github.com/caolan/highland/pull/42正确修复此问题,现在已合并,因此从版本1.14.0开始,该错误将不再可重现