Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created April 9, 2019 08:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/3924dd09d0ce55d7acc6cc4819379b92 to your computer and use it in GitHub Desktop.
Save akirattii/3924dd09d0ce55d7acc6cc4819379b92 to your computer and use it in GitHub Desktop.
NodeJS: Get an absolute path from any path.
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
*/
Copy link

ghost commented Jun 18, 2020

Thanks this really helped me out with some express sendFile stuff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment