Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. const path = require("path");
  2. const os = require("os");
  3.  
  4. console.log("/foo/bar/file.txt", "=>", getAbsolutePath("/foo/bar/file.txt"));
  5. console.log("foo/bar/file.txt", "=>", getAbsolutePath("foo/bar/file.txt"));
  6. console.log("../../foo/bar/file.txt", "=>", getAbsolutePath("../../foo/bar/file.txt"));
  7. console.log("~/file.txt", "=>", getAbsolutePath("~/file.txt"));
  8. console.log("/~/file.txt", "=>", getAbsolutePath("/~/file.txt"));
  9. console.log("/../../file.txt", "=>", getAbsolutePath("/../../file.txt"));
  10.  
  11. function getAbsolutePath(filepath, delim = "/") {
  12. // Dependencies:
  13. // const path = require("path");
  14. // const os = require("os");
  15. if (filepath == null || typeof filepath !== "string") throw Error("invalid filepath");
  16. const homedir = os.homedir();
  17. filepath = filepath.replace(/\~/g, homedir + delim);
  18. return path.resolve(filepath);
  19. }
  20.  
  21. /* output:
  22. /foo/bar/file.txt => /foo/bar/file.txt
  23. foo/bar/file.txt => /home/<user>/xxx/yyy/foo/bar/file.txt
  24. ../../foo/bar/file.txt => /home/<user>/foo/bar/file.txt
  25. ~/file.txt => /home/<user>/file.txt
  26. /~/file.txt => /home/<user>/file.txt
  27. /../../file.txt => /file.txt
  28. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement