1 | import fs, {promises as fsPromises} from 'fs';
|
2 |
|
3 | async function isType(fsStatType, statsMethodName, filePath) {
|
4 | if (typeof filePath !== 'string') {
|
5 | throw new TypeError(`Expected a string, got ${typeof filePath}`);
|
6 | }
|
7 |
|
8 | try {
|
9 | const stats = await fsPromises[fsStatType](filePath);
|
10 | return stats[statsMethodName]();
|
11 | } catch (error) {
|
12 | if (error.code === 'ENOENT') {
|
13 | return false;
|
14 | }
|
15 |
|
16 | throw error;
|
17 | }
|
18 | }
|
19 |
|
20 | function isTypeSync(fsStatType, statsMethodName, filePath) {
|
21 | if (typeof filePath !== 'string') {
|
22 | throw new TypeError(`Expected a string, got ${typeof filePath}`);
|
23 | }
|
24 |
|
25 | try {
|
26 | return fs[fsStatType](filePath)[statsMethodName]();
|
27 | } catch (error) {
|
28 | if (error.code === 'ENOENT') {
|
29 | return false;
|
30 | }
|
31 |
|
32 | throw error;
|
33 | }
|
34 | }
|
35 |
|
36 | export const isFile = isType.bind(null, 'stat', 'isFile');
|
37 | export const isDirectory = isType.bind(null, 'stat', 'isDirectory');
|
38 | export const isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
|
39 | export const isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
|
40 | export const isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
|
41 | export const isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
|