UNPKG

1.61 kBJavaScriptView Raw
1/*!
2 * read-multiple-files | MIT (c) Shinnosuke Watanabe
3 * https://github.com/shinnn/read-multiple-files
4*/
5'use strict';
6
7const inspectWithKind = require('inspect-with-kind');
8const {readFile} = require('graceful-fs');
9const runParalell = require('run-parallel');
10const stripBom = require('strip-bom');
11const stripBomBuf = require('strip-bom-buf');
12
13const ARG_ERR = 'Expected 2 or 3 arguments (paths: <Array|Set>[, options: <Object>], callback: <Function>)';
14
15module.exports = function readMultipleFiles(...args) {
16 const argLen = args.length;
17
18 if (argLen !== 2 && argLen !== 3) {
19 throw new RangeError(`${ARG_ERR}, but got ${
20 argLen === 1 ? '1 argument' : `${argLen || 'no'} arguments`
21 } instead.`);
22 }
23
24 const [filePaths, options, cb] = argLen === 3 ? args : [args[0], {}, args[1]];
25
26 if (typeof cb !== 'function') {
27 throw new TypeError(inspectWithKind(cb) +
28 ' is not a function. Last argument to read-multiple-files must be a callback function.');
29 }
30
31 if (!Array.isArray(filePaths) && !(filePaths instanceof Set)) {
32 throw new TypeError(inspectWithKind(filePaths) +
33 ' is neither Array nor Set. First Argument to read-multiple-files must be file paths (<Array> or <Set>).');
34 }
35
36 runParalell([...filePaths].map(filePath => done => readFile(filePath, options, done)), (err, results) => {
37 if (err) {
38 cb(err);
39 return;
40 }
41
42 if (results.length === 0) {
43 cb(null, results);
44 return;
45 }
46
47 if (Buffer.isBuffer(results[0])) {
48 cb(null, results.map(stripBomBuf));
49 return;
50 }
51
52 cb(null, results.map(stripBom));
53 });
54};