Node.js

浅谈node中的resolve

2020-02-26  本文已影响0人  景元合

前言

今天学习node时候对于path.resolve()各种情况不太了解,只知道是拼接路径,但是具体规则不清楚,于是写这篇小文章记载一下。

path.resolve([...paths])

新增于: v0.3.4

我们可以分三种情况去总结\color{red}{resolve}

1.传入的参数不带/或者为./

const {resolve}=require('path');
;(async ()=>{
    console.log(resolve(__dirname));
    console.log(resolve('./a'));
    console.log(resolve(__dirname,'./a'));
    console.log(resolve(__dirname,'./a','./b'))
})()
//F:\学习\douban-koa\server\tasks
//F:\学习\douban-koa\a
//F:\学习\douban-koa\server\tasks\a
//F:\学习\douban-koa\server\tasks\a\b

2.传入的参数带../

const {resolve}=require('path');
;(async ()=>{
    console.log(resolve('../a'));
    console.log(resolve(__dirname,'../a'));
    console.log(resolve(__dirname,'./a','../c','../b'))
})()
//F:\学习\a
//F:\学习\douban-koa\server\a
//F:\学习\douban-koa\server\tasks\b

3.传入的参数带/
以最后一个出现的带/参数为起始位置,不接受当前路径前的任何参数,包括文件所在路径:

const {resolve}=require('path');
;(async ()=>{
    console.log('/a')
    console.log(__dirname,'/a')
    console.log(resolve('./a', '/b', '/c'));
    console.log(resolve('./a', '/b', '/c', './d'));
    console.log(resolve('./a', '/b', '/c', './d', '../f'))
})()
///a
//F:\学习\douban-koa\server\tasks /a
//F:\c
//F:\c\d
//F:\c\f
``
上一篇下一篇

猜你喜欢

热点阅读