UNPKG

1.17 kBJavaScriptView Raw
1import fs, {promises as fsPromises} from 'fs';
2
3async 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
20function 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
36export const isFile = isType.bind(null, 'stat', 'isFile');
37export const isDirectory = isType.bind(null, 'stat', 'isDirectory');
38export const isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
39export const isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
40export const isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
41export const isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');