1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | const inspectWithKind = require('inspect-with-kind');
|
8 | const {readFile} = require('graceful-fs');
|
9 | const runParalell = require('run-parallel');
|
10 | const stripBom = require('strip-bom');
|
11 | const stripBomBuf = require('strip-bom-buf');
|
12 |
|
13 | const ARG_ERR = 'Expected 2 or 3 arguments (paths: <Array|Set>[, options: <Object>], callback: <Function>)';
|
14 |
|
15 | module.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 | };
|