30秒学会 JavaScript 片段 · 2023年8月9日

30秒学会 JavaScript 片段 – Convert to absolute path

Converts a tilde path to an absolute path.

  • Use String.prototype.replace() with a regular expression and os.homedir() to replace the ~ in the start of the path with the home directory.

代码实现

import { homedir } from 'os';

const untildify = str => str.replace(/^~($|\/|\\)/, `${homedir()}$1`);

untildify('~/node'); // '/Users/aUser/node'

翻译自:https://www.30secondsofcode.org/js/s/convert-to-absolute-path