You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.1 KiB

4 years ago
  1. 'use strict';
  2. module.exports = readdirAsync;
  3. const maybe = require('call-me-maybe');
  4. const DirectoryReader = require('../directory-reader');
  5. let asyncFacade = {
  6. fs: require('fs'),
  7. forEach: require('./for-each'),
  8. async: true
  9. };
  10. /**
  11. * Returns the buffered output from an asynchronous {@link DirectoryReader},
  12. * via an error-first callback or a {@link Promise}.
  13. *
  14. * @param {string} dir
  15. * @param {object} [options]
  16. * @param {function} [callback]
  17. * @param {object} internalOptions
  18. */
  19. function readdirAsync (dir, options, callback, internalOptions) {
  20. if (typeof options === 'function') {
  21. callback = options;
  22. options = undefined;
  23. }
  24. return maybe(callback, new Promise(((resolve, reject) => {
  25. let results = [];
  26. internalOptions.facade = asyncFacade;
  27. let reader = new DirectoryReader(dir, options, internalOptions);
  28. let stream = reader.stream;
  29. stream.on('error', err => {
  30. reject(err);
  31. stream.pause();
  32. });
  33. stream.on('data', result => {
  34. results.push(result);
  35. });
  36. stream.on('end', () => {
  37. resolve(results);
  38. });
  39. })));
  40. }