![](/img/trans.png)
[英]How are absolute or relative file paths of the custom modules resolved in node.js?
[英]Node JS Absolute paths using windows % variables treated as relative
我正在Node.js腳本中使用fs.unlinkSync()
方法,以便刪除位於Appdata
目錄中的文件。
定位Appdata
目錄的最佳實踐是使用%appdata%
指定路徑,因此在我的代碼中:
var filePath = '%appdata%/some/path/file.ext';
fs.unlinkSync(filePath);
問題是返回錯誤,指示路徑錯誤,因為它正在嘗試查找類似以下內容的內容:
C:\my\project\%appdata%\some\path\file.ext
顯然不存在。
因此,我正在尋找將%appdata%
解析為C:\\Users\\user\\AppData\\Roaming
的最佳方法。
希望我可以按照以下方式做點事情:
var filePath = resolveToAbsolutePath('%appdata%/some/path/file.ext');
fs.unlinkSync(filePath);
任何幫助都將受到贊賞。
筆記:
您可以使用將解析路徑的函數來解析它:
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.