Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const path = require("path");
- const os = require("os");
- console.log("/foo/bar/file.txt", "=>", getAbsolutePath("/foo/bar/file.txt"));
- console.log("foo/bar/file.txt", "=>", getAbsolutePath("foo/bar/file.txt"));
- console.log("../../foo/bar/file.txt", "=>", getAbsolutePath("../../foo/bar/file.txt"));
- console.log("~/file.txt", "=>", getAbsolutePath("~/file.txt"));
- console.log("/~/file.txt", "=>", getAbsolutePath("/~/file.txt"));
- console.log("/../../file.txt", "=>", getAbsolutePath("/../../file.txt"));
- function getAbsolutePath(filepath, delim = "/") {
- // Dependencies:
- // const path = require("path");
- // const os = require("os");
- if (filepath == null || typeof filepath !== "string") throw Error("invalid filepath");
- const homedir = os.homedir();
- filepath = filepath.replace(/\~/g, homedir + delim);
- return path.resolve(filepath);
- }
- /* output:
- /foo/bar/file.txt => /foo/bar/file.txt
- foo/bar/file.txt => /home/<user>/xxx/yyy/foo/bar/file.txt
- ../../foo/bar/file.txt => /home/<user>/foo/bar/file.txt
- ~/file.txt => /home/<user>/file.txt
- /~/file.txt => /home/<user>/file.txt
- /../../file.txt => /file.txt
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement