index.mjs 517 B

12345678910111213141516171819202122
  1. import { dirname, resolve } from 'path';
  2. import { readdir, stat } from 'fs';
  3. import { promisify } from 'util';
  4. const toStats = promisify(stat);
  5. const toRead = promisify(readdir);
  6. export default 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. }