index.js 534 B

1234567891011121314151617181920212223
  1. const { dirname, resolve } = require('path');
  2. const { readdir, stat } = require('fs');
  3. const { promisify } = require('util');
  4. const toStats = promisify(stat);
  5. const toRead = promisify(readdir);
  6. module.exports = async function (start, callback) {
  7. let dir = resolve('.', start);
  8. let tmp, stats = await toStats(dir);
  9. if (!stats.isDirectory()) {
  10. dir = dirname(dir);
  11. }
  12. while (true) {
  13. tmp = await callback(dir, await toRead(dir));
  14. if (tmp) return resolve(dir, tmp);
  15. dir = dirname(tmp = dir);
  16. if (tmp === dir) break;
  17. }
  18. }