[英]Node JS Absolute paths using windows % variables treated as relative
I am using fs.unlinkSync()
method in a Node.js script, in order to remove a file located in Appdata
directory. 我正在Node.js脚本中使用
fs.unlinkSync()
方法,以便删除位于Appdata
目录中的文件。
Best practice of locating the Appdata
dir is specifying a path using %appdata%
, so in my code: 定位
Appdata
目录的最佳实践是使用%appdata%
指定路径,因此在我的代码中:
var filePath = '%appdata%/some/path/file.ext';
fs.unlinkSync(filePath);
The problem is an error is returned, indicating bad path, because it's trying to locate something like: 问题是返回错误,指示路径错误,因为它正在尝试查找类似以下内容的内容:
C:\my\project\%appdata%\some\path\file.ext
Which obviously doesn't exist. 显然不存在。
So I'm looking for the best method to resolve %appdata%
into C:\\Users\\user\\AppData\\Roaming
. 因此,我正在寻找将
%appdata%
解析为C:\\Users\\user\\AppData\\Roaming
的最佳方法。
Hopefully I can do something along the lines of: 希望我可以按照以下方式做点事情:
var filePath = resolveToAbsolutePath('%appdata%/some/path/file.ext');
fs.unlinkSync(filePath);
Any kind of help is appreciated. 任何帮助都将受到赞赏。
Notes: 笔记:
You can resolve it using a function that will resolve the path: 您可以使用将解析路径的函数来解析它:
function resolveToAbsolutePath(path) {
return path.replace(/%([^%]+)%/g, function(_, key) {
return process.env[key];
});
}
resolveToAbsolutePath('%LOCALAPPDATA%\\Google\\Chrome\\Application');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.