简体   繁体   English

使用Windows%变量的Node JS绝对路径被视为相对路径

[英]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: 笔记:

  1. Nope, the issue is unrelated to using forward slashes instead of backslashes. 不会,问题与使用正斜杠而不是反斜杠无关。
  2. This is different than using environment variables , as I get the paths externally, and I need to be able to resolve % paths as well. 这与使用环境变量不同 ,因为我从外部获取路径,并且还需要能够解析%路径。 I'm interested in generalising the solution, rather than manually replacing paths with environment variable data. 我有兴趣推广解决方案,而不是用环境变量数据手动替换路径。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM