Created
April 9, 2019 08:03
-
-
Save akirattii/3924dd09d0ce55d7acc6cc4819379b92 to your computer and use it in GitHub Desktop.
NodeJS: Get an absolute path from any path.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks this really helped me out with some express sendFile stuff.