在为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 no?
发布于 2016-08-13 20:34:13
这很可能是因为Array.prototype.map和_.map向提供的映射函数传递了三个参数(值、索引和集合),而R.map只传递了值。
在您的示例中,fs.createReadStream被赋予数组索引作为其第二个参数,而它需要的是options对象或字符串,从而导致"options" argument must be a string or an object错误。如果您想以这种方式使用Array.prototype.map或_.map,则需要将方法调用包装在一个函数中,以防止额外的参数:
[tmp1, tmp2].map(p => fs.createReadStream(p))https://stackoverflow.com/questions/38932553
复制相似问题