42 lines · typescript
1import * as os from "os";2import * as path from "path";3 4/**5 * Expands the character `~` to the user's home directory6 */7export function expandUser(file_path: string): string {8 if (os.platform() == "win32") {9 return file_path;10 }11 12 if (!file_path) {13 return "";14 }15 16 if (!file_path.startsWith("~")) {17 return file_path;18 }19 20 const path_len = file_path.length;21 if (path_len == 1) {22 return os.homedir();23 }24 25 if (file_path.charAt(1) == path.sep) {26 return path.join(os.homedir(), file_path.substring(1));27 }28 29 const sep_index = file_path.indexOf(path.sep);30 const user_name_end = sep_index == -1 ? file_path.length : sep_index;31 const user_name = file_path.substring(1, user_name_end);32 try {33 if (user_name == os.userInfo().username) {34 return path.join(os.homedir(), file_path.substring(user_name_end));35 }36 } catch (err) {37 return file_path;38 }39 40 return file_path;41}42