![](/img/trans.png)
[英]Node.js: Check if file is an symbolic link when iterating over directory with 'fs'
[英]Symbolic-Link always points to its parent directory
放置當前目錄以外的符號鏈接不起作用,因為它們總是指向當前目錄
我在 Windows 10,我錯過了什么?
fs.symlink('./testFile', './testDir/testSymLink', function(err){ // creates a symbolic- link in the 'testDir' subfolder relative to the current directory
if(err) console.log(err);
});
fs.readlink('./testDir/testSymlink',function(err, links){ // reads the created symbolic link
if(err) console.log(err);
console.log(links); // -> '.\testFile' (points to the current directory not to the parent directory)
});
fs.readFile('./testDir/testSymlink.txt', function(err, data){ // file doesn't exist
if(err) console.log(err); // -> ENOENT no such file or directory
console.log(data); // -> undefined
});
符號鏈接已創建(我們可以讀取)但指向其當前目錄.\testFile
它應該指向其參考文件為..\testFile
的父目錄
symlink()
方法的第一個參數是創建的符號鏈接使用的目標位置。
重要的是要知道符號鏈接在傳遞時使用第一個參數! (不將其解析為絕對路徑!)
這是棘手的部分,因為上面的第一個參數是./testFile
符號鏈接將使用此路徑來引用其自己目錄中的“testFile”(而不是在父目錄中)
解決方案:
1:上面的代碼可以這樣固定( testSymLink
目錄下的testDir
引用了父目錄下的testFile
)
fs.symlink('../testFile', './testDir/testSymLink', function(err){
if(err) console.log(err);
});
2:在symlink()
方法中將絕對路徑作為第一個參數傳遞(這將為您節省很多麻煩!)
fs.symlink(/* absolute path */, './testDir/testSymLink', function(err){
if(err) console.log(err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.