node中的path模块

作者 : 开心源码 本文共2091个字,预计阅读时间需要6分钟 发布时间: 2022-05-13 共253人阅读

path模块,其实还是在webpack中用过一下下,至于node,还没开始用。这个模块算是基础,当作是预习一下。

path模块方法还是有几个的,这边只学习几个认为有必要、能用到的几个方法。

开始之前先看看两个输出:

console.log(__dirname);

E:\mydata\project\bootstrap\html\coding

dirname翻译过来是目录名,表示当前js所在文件夹的绝对路径

console.log(__filename);

E:\mydata\project\bootstrap\html\coding\node-path.js

表示当前js所在的绝对路径与文件名

一个是文件夹,一个是文件。

引入path模块都一样:

let path = require(‘path’);

path.resolve:

webpack配置output的时候使用过,相当于cd命令:

console.log(path.resolve(__dirname, ‘../../’, ‘css’, ‘../’, ‘html’))

已经知道了__dirname是当前js所在文件夹目录,所以是在coding文件夹里面,相当于下面的步骤:

cd E:\mydata\project\bootstrap\html\coding

cd ../../

cd css

cd ../

cd html

所以输出:

E:\mydata\project\bootstrap\htm

path.extname:

console.log(path.extname(‘a.vue’))//vueconsole.log(path.extname(‘b.js’))//jsconsole.log(path.extname(‘c.html’))//htmlconsole.log(path.extname(‘d.’))//.console.log(path.extname(‘e’))//

返回后缀名,以.结尾返回.,无扩展名也无.则返回空。

path.parse:

console.log(path.parse(‘/html/coding/coding.html’))

输出:

{ root: ‘/’,//跟目录 dir: ‘/html/coding’,//当前文件所在路径

base: ‘coding.html’,//文件名 ext: ‘.html’,//文件后缀名 name: ‘coding’//当前文件所在文件夹名}

path.dirname:

dirname方法和__dirname有点相同,返回当前文件或者者文件夹所在目录:

console.log(path.dirname(‘/html/coding/coding.html’))

/html/coding

console.log(path.dirname(‘/html/coding’))

/html

path.basename:

返回文件名,其实就是最后的名字:

console.log(path.basename(‘/html/coding/coding.html’, ‘.html’))

coding

console.log(path.basename(‘/html/coding/coding.html’))

coding.html

console.log(path.basename(‘/html/coding’))

coding

两个参数,第一个是路径,第二个是可选参数,表示不输出后缀名。

path.relative:

接收两个参数,(from, to),表示从from路径到to路径的相对路径:

console.log(path.relative(‘/html/coding/coding.html’, ‘/css’))

……\css

path.join:

这个就是拼接两个路径,简单点说就是拼接字符串:

console.log(path.join(‘/html’, ‘coding’))

\html\coding

有一点比较重要,这个方法可以根据不同平台规范化路径,比方我电脑是Windows的,那么输出\,假如是Unix,就是/。

path.normalize:

字面上是规范路径,其实就是把尾巴不规范的去除:

console.log(path.normalize(‘/html/coding’))

\html\coding

console.log(path.normalize(‘/html/coding/’))

\html\coding\

console.log(path.normalize(‘/html/coding/.’))

\html\coding

console.log(path.normalize(‘/html/coding/coding.html/..’))

\html\coding

也就是能根据系统规范路径。

咋一看如同几个方法有些鸡肋,但是要考虑动态路径或者者是根据系统操作等情况,这些方法就非常重要。

大概就这几个了,path模块还有好几个方法,比方delimiter、format、isabsolute、posix等,要是真遇见少量场景需要可以查文档。

image

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » node中的path模块

发表回复