在为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
否?
答案 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))