index.js 1.2 KB

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