I am new to nodejs. Can node resolve ~ (unix home directory) example ~foo, ~bar to /home/foo, /home/bar
> path.normalize(\'~mvaidya\') \'~mvaidya\' > path.resolve(
This is a combination of some of the previous answers with a little more safety added in.
/**
* Resolves paths that start with a tilde to the user's home directory.
*
* @param {string} filePath '~/GitHub/Repo/file.png'
* @return {string} '/home/bob/GitHub/Repo/file.png'
*/
function resolveTilde (filePath) {
const os = require('os');
if (!filePath || typeof(filePath) !== 'string') {
return '';
}
// '~/folder/path' or '~' not '~alias/folder/path'
if (filePath.startsWith('~/') || filePath === '~') {
return filePath.replace('~', os.homedir());
}
return filePath;
}
os.homedir()
instead of process.env.HOME
.os.homedir()
if a non-string is passed in instead of returning empty string.~/
or is just ~
, to not replace other aliases like ~stuff/
..slice(1)
.