2

request当我通过映射它已经是空数组时,我在处理 nodejs 流时遇到问题。

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);
});
4

1 回答 1

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 版本开始,该错误将不再可重现

于 2014-02-22T20:07:41.400 回答