aboutsummaryrefslogtreecommitdiff
path: root/node_modules/@mrmlnc/readdir-enhanced/lib/async/index.js
blob: 677e0b654be48f8a181e823ce673dd61a6e95ce8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';

module.exports = readdirAsync;

const maybe = require('call-me-maybe');
const DirectoryReader = require('../directory-reader');

let asyncFacade = {
  fs: require('fs'),
  forEach: require('./for-each'),
  async: true
};

/**
 * Returns the buffered output from an asynchronous {@link DirectoryReader},
 * via an error-first callback or a {@link Promise}.
 *
 * @param {string} dir
 * @param {object} [options]
 * @param {function} [callback]
 * @param {object} internalOptions
 */
function readdirAsync (dir, options, callback, internalOptions) {
  if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }

  return maybe(callback, new Promise(((resolve, reject) => {
    let results = [];

    internalOptions.facade = asyncFacade;

    let reader = new DirectoryReader(dir, options, internalOptions);
    let stream = reader.stream;

    stream.on('error', err => {
      reject(err);
      stream.pause();
    });
    stream.on('data', result => {
      results.push(result);
    });
    stream.on('end', () => {
      resolve(results);
    });
  })));
}