-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.ts
73 lines (62 loc) · 2.47 KB
/
index.ts
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import * as fs from "fs";
import { DirectoryReader } from "../directory-reader";
import { Callback, Options, Stats } from "../types-public";
import { asyncForEach as forEach } from "./for-each";
const asyncFacade = { fs, forEach };
/**
* A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` function
* that adds support for additional features like filtering, recursion, absolute paths, etc.
*/
export function readdirAsync(dir: string, callback: Callback<string[]>): void;
/**
* A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` function
* that adds support for additional features like filtering, recursion, absolute paths, etc.
*/
export function readdirAsync(dir: string, options: undefined, callback: Callback<string[]>): void;
/**
* A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` function
* that adds support for additional features like filtering, recursion, absolute paths, etc.
*/
export function readdirAsync(dir: string, options: Options & { stats?: false }, callback: Callback<string[]>): void;
/**
* Asynchronous `readdir()` that returns an array of `Stats` objects via a callback.
*/
export function readdirAsync(dir: string, options: Options & { stats: true }, callback: Callback<Stats[]>): void;
/**
* Asynchronous `readdir()` that returns its results via a Promise.
*/
export function readdirAsync(dir: string, options?: Options & { stats?: false }): Promise<string[]>;
/**
* Asynchronous `readdir()` that returns an array of `Stats` objects via a Promise.
*/
export function readdirAsync(dir: string, options: Options & { stats: true }): Promise<Stats[]>;
export function readdirAsync<T>(dir: string, options: Options | Callback<T[]> | undefined, callback?: Callback<T[]>): Promise<T[]> | void {
if (typeof options === "function") {
callback = options;
options = undefined;
}
let promise = new Promise<T[]>((resolve, reject) => {
let results: T[] = [];
let reader = new DirectoryReader(dir, options as Options, asyncFacade);
let stream = reader.stream;
stream.on("error", (err: Error) => {
reject(err);
stream.pause();
});
stream.on("data", (result: T) => {
results.push(result);
});
stream.on("end", () => {
resolve(results);
});
});
if (callback) {
promise.then(
(results: T[]) => callback!(null, results),
(err: Error) => callback!(err, undefined as unknown as T[])
);
}
else {
return promise;
}
}