resolve-symlink.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. const readCmdShim = require("read-cmd-shim");
  3. const fs = require("fs-extra");
  4. const log = require("npmlog");
  5. const path = require("path");
  6. module.exports.resolveSymlink = resolveSymlink;
  7. function resolveSymlink(filePath) {
  8. log.silly("resolveSymlink", filePath);
  9. let result;
  10. if (process.platform === "win32") {
  11. result = resolveWindowsSymlink(filePath);
  12. } else {
  13. result = resolvePosixSymlink(filePath);
  14. }
  15. log.verbose("resolveSymlink", [filePath, result]);
  16. return result;
  17. }
  18. function resolveSymbolicLink(filePath) {
  19. const lstat = fs.lstatSync(filePath);
  20. const resolvedPath = lstat.isSymbolicLink()
  21. ? path.resolve(path.dirname(filePath), fs.readlinkSync(filePath))
  22. : false;
  23. return {
  24. resolvedPath,
  25. lstat,
  26. };
  27. }
  28. function resolvePosixSymlink(filePath) {
  29. return resolveSymbolicLink(filePath).resolvedPath;
  30. }
  31. function resolveWindowsSymlink(filePath) {
  32. const { resolvedPath, lstat } = resolveSymbolicLink(filePath);
  33. if (lstat.isFile() && !resolvedPath) {
  34. try {
  35. return path.resolve(path.dirname(filePath), readCmdShim.sync(filePath));
  36. } catch (e) {
  37. return false;
  38. }
  39. }
  40. return resolvedPath && path.resolve(resolvedPath);
  41. }