I'm trying to check if a directory exists as part of a command-line app in node.js. However, fs
doesn't seem to understand ~/
. For example, the following returns false...
> fs.existsSync('~/Documents')
false
...but this returns true...
> fs.existsSync('/Users/gtmtg/Documents')
true
...even though they're both the same thing.
Why does this happen, and is there are workaround for this? Thanks in advance!
这是因为命令shell支持~/
,而不是文件系统API。
As an alternative, the user's home path (~) is usually stored in the environment variable HOME. So you can try using something like this:
fs.existsSync(`${process.env.HOME}/Documents`);
Or, you can create a function to process the tilde character, like this:
function parseTildeHome(inputPath) {
return inputPath.replace('~', process.env.HOME);
}
fs.existsSync(parseTildeHome('~/Documents'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.