path.resolve源码实现(简单版)

//解析文件路径。类似于path.resolve
  resolve(...paths){
        let resolvePath = '';
        let isAbsolutePath = false;
        for(let i = paths.length-1; i > -1; i--){
            let path = paths[i];
            if(isAbsolutePath){
                break;
            }
            if(!path){
                continue
            }
            resolvePath = path + '/' + resolvePath;
            isAbsolutePath = path.charCodeAt(0) === 47;
        }
        if(/^\/+$/.test(resolvePath)){
            resolvePath = resolvePath.replace(/(\/+)/,'/')
        }else{
            resolvePath = resolvePath.replace(/(?!^)\w+\/+\.{2}\//g, '')
            .replace(/(?!^)\.\//g,'')
            .replace(/\/+$/, '')
        }
        return resolvePath;
    }
console.log(resolve('/aa','../bb','cc','dd'))
console.log(resolve('/aa','../bb','./cc','dd'))
console.log(resolve('/','/system','user','userIndex'))
posted @ 2021-12-11 17:35  littleboyck  阅读(529)  评论(0编辑  收藏  举报