var fs = require('fs'); var randomFileName = './extra/fileForReadLink-' + String(Math.random()).slice(2, 6) + '.txt'; fs.symlinkSync('./extra/fileForReadLink.txt', randomFileName); fs.readlink(randomFileName, 'utf8', function(err, linkString){ if(err) throw err; console.log('链接文件内容: ' + linkString); });
类似终端下直接运行readlink。对于软链接文件,效果同上面代码。对于硬链接,没有输出。
➜ extra git:(master) ✗ readlink fileForReadLink-9827.txt
./extra/fileForReadLink.txt
➜ extra git:(master) ✗ readlink fileForLinkHard.txt
➜ extra git:(master) ✗ readlink fileForLinkSoft.txt
./extra/fileForLink.txt
真实路径
fs.realpath(path[, options], callback) fs.realpathSync(path[, options])
例子:(不能作用于软链接?)