Published on

Converting Tilde Path like ~/dev to Absolute Path in Node.js

Authors

Tilde paths are a convenient way to represent paths in shells, but they may not work with Node.js properly which typically requires absolute paths.

For such cases, we can just use untildify npm package and convert tilde to absolute path instantly.

Dependency

npm install untildify

Snippet

import untildify from 'untildify';

untildify('~/Dropbox');
//=> '/Users/AshikNesin/Dropbox'

How does it work?

We're using Node.js build-in homedir() function to get home directory and replace that with our tilde path.

// Simplified version of untildify package
import os from "node:os";

const homeDirectory = os.homedir();

console.log(`homeDirectory: ${homeDirectory}`);
// 👉 homeDirectory: /home/runner

const pathWithTilde = "~/Dropbox";

console.log(`pathWithTilde: ${pathWithTilde}`);
// 👉 pathWithTilde: ~/Dropbox

// Now replace "~" with "homeDirectory"
const absolutePath = homeDirectory + pathWithTilde.slice(1).replace(/\\/g, "/");

console.log(`absolutePath: ${absolutePath}`);
// 👉 absolutePath: /home/runner/Dropbox

Happy converting paths!