node.js中的fs.realpathSync方法使用说明
方法说明:
同步版的fs.realpath()。
语法:
fs.realpathSync(path,[cache])
由于该方法属于fs模块,使用前需要引入fs模块(varfs=require(“fs”))
接收参数:
path 路径
cache 可选,一个文字的映射路径可用于强制一个特定的路径解决或避免额外的fs.stat需要知道真正的路径对象。
例子:
varfs=require('fs');
//点号表示当前文件所在路径
varstr=fs.realpathSync('.');
console.log(str);
源码:
fs.realpathSync=functionrealpathSync(p,cache){
//makepisabsolute
p=pathModule.resolve(p);
if(cache&&Object.prototype.hasOwnProperty.call(cache,p)){
returncache[p];
}
varoriginal=p,
seenLinks={},
knownHard={};
//currentcharacterpositioninp
varpos;
//thepartialpathsofar,includingatrailingslashifany
varcurrent;
//thepartialpathwithoutatrailingslash(exceptwhenpointingataroot)
varbase;
//thepartialpathscannedinthepreviousround,withslash
varprevious;
start();
functionstart(){
//Skipoverroots
varm=splitRootRe.exec(p);
pos=m[0].length;
current=m[0];
base=m[0];
previous='';
//Onwindows,checkthattherootexists.Onunixthereisnoneed.
if(isWindows&&!knownHard[base]){
fs.lstatSync(base);
knownHard[base]=true;
}
}
//walkdownthepath,swappingoutlinkedpathpartsfortheirreal
//values
//NB:p.lengthchanges.
while(pos<p.length){
//findthenextpart
nextPartRe.lastIndex=pos;
varresult=nextPartRe.exec(p);
previous=current;
current+=result[0];
base=previous+result[1];
pos=nextPartRe.lastIndex;
//continueifnotasymlink
if(knownHard[base]||(cache&&cache[base]===base)){
continue;
}
varresolvedLink;
if(cache&&Object.prototype.hasOwnProperty.call(cache,base)){
//someknownsymboliclink.noneedtostatagain.
resolvedLink=cache[base];
}else{
varstat=fs.lstatSync(base);
if(!stat.isSymbolicLink()){
knownHard[base]=true;
if(cache)cache[base]=base;
continue;
}
//readthelinkifitwasn'treadbefore
//dev/inoalwaysreturn0onwindows,soskipthecheck.
varlinkTarget=null;
if(!isWindows){
varid=stat.dev.toString(32)+':'+stat.ino.toString(32);
if(seenLinks.hasOwnProperty(id)){
linkTarget=seenLinks[id];
}
}
if(util.isNull(linkTarget)){
fs.statSync(base);
linkTarget=fs.readlinkSync(base);
}
resolvedLink=pathModule.resolve(previous,linkTarget);
//trackthis,ifgivenacache.
if(cache)cache[base]=resolvedLink;
if(!isWindows)seenLinks[id]=linkTarget;
}
//resolvethelink,thenstartover
p=pathModule.resolve(resolvedLink,p.slice(pos));
start();
}
if(cache)cache[original]=p;
returnp;
};