index.js 1.1 KB

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