zl程序教程

您现在的位置是:首页 >  后端

当前栏目

node.js中的path.join方法使用说明

JS方法Node 使用 说明 Join path
2023-06-13 09:15:32 时间

方法说明:

将多个参数组合成一个path(详细请看例子)

语法:

复制代码代码如下:


path.join([path1],[path2],[...])

由于该方法属于path模块,使用前需要引入path模块(varpath=require(“path”))

例子:

复制代码代码如下:


path.join("/foo","bar","baz/asdf","quux","..")
//returns
"/foo/bar/baz/asdf"
path.join("foo",{},"bar")
//throwsexception
TypeError:Argumentstopath.joinmustbestrings

源码:

复制代码代码如下:
//windowsversion
 exports.join=function(){
   functionf(p){
     if(!util.isString(p)){
       thrownewTypeError("Argumentstopath.joinmustbestrings");
     }
     returnp;
   }
 
   varpaths=Array.prototype.filter.call(arguments,f);
   varjoined=paths.join("\\");
 
   //Makesurethatthejoinedpathdoesn"tstartwithtwoslashes,because
   //normalize()willmistakeitforanUNCpaththen.
   //
   //Thisstepisskippedwhenitisveryclearthattheuseractually
   //intendedtopointatanUNCpath.Thisisassumedwhenthefirst
   //non-emptystringargumentsstartswithexactlytwoslashesfollowedby
   //atleastonemorenon-slashcharacter.
   //
   //Notethatfornormalize()totreatapathasanUNCpathitneedsto
   //haveatleast2components,sowedon"tfilterforthathere.
   //ThismeansthattheusercanusejointoconstructUNCpathsfrom
   //aservernameandasharename;forexample:
   //path.join("//server","share")->"\\\\server\\share\")
   if(!/^[\\\/]{2}[^\\\/]/.test(paths[0])){
     joined=joined.replace(/^[\\\/]{2,}/,"\\");
   }
 
   returnexports.normalize(joined);
 };