为什么Ramda在本例Array.map或Lodash没有的示例中工作?

时间:2016-08-13 12:06:22

标签: ramda.js

在为this SO question撰写示例的过程中,出现了这个问题:

为什么本地Array.map在使用时会抛出错误:

[tmp1, tmp2].map(fs.createReadStream)
  .forEach(stream => stream.pipe(jsonStream));


fs.js:1664
    throw new TypeError('"options" argument must be a string or an object');
    ^

TypeError: "options" argument must be a string or an object
    at new ReadStream (fs.js:1664:11)
    at fs.createReadStream (fs.js:1649:10)
    at Array.map (native)

与lodash类似......但它与ramda一起工作正常。

// Same error:
_.map([tmp1, tmp2], fs.createReadStream)
  .forEach(stream => stream.pipe(jsonStream));

// Works fine:
R.map(fs.createReadStream, [tmp1, tmp2])
  .forEach(stream => stream.pipe(jsonStream));

请注意,这是引用问题的完整代码:

var fs = require('fs');
var path = require('path');
var JSONStream = require('JSONStream');

var tmp1 = path.join(__dirname, 'data', 'tmp1.json');
var tmp2 = path.join(__dirname, 'data', 'tmp2.json');

var jsonStream = JSONStream.parse();
jsonStream.on('data', function (data) {
  console.log('---\nFrom which file does this data come from?');
  console.log(data);
});

[tmp1, tmp2].map(p => {
  return fs.createReadStream(p);
}).forEach(stream => {
  stream.pipe(jsonStream);
});

fs.createReadStream的第二个参数应为undefined否?

1 个答案:

答案 0 :(得分:3)

这很可能是由于Array.prototype.map_.map将三个参数传递给提供的映射函数(值,索引和集合),而R.map仅传递该值。

在您的示例中,fs.createReadStream被赋予数组索引作为其第二个参数,其中它需要选项对象或字符串,从而导致"options" argument must be a string or an object错误。如果要以这种方式使用Array.prototype.map_.map,则需要将方法调用包装在函数中以防止额外的参数:

[tmp1, tmp2].map(p => fs.createReadStream(p))