node
node-path
使用之前首先引入 path
import path from 'path';
1.path.join()
- 使用特定的分隔符作为定界符将所有给定的 path 片段连接在一起,然后规范化生成的路径。(拼接路径)
path.join('http://localhost:4001/', '/news') // http:\localhost:4001\news
- windows 中
var str=path.join('/foo', 'bar', 'baz/asdf'); // \foo\bar\baz\asdf
- windows 中
2.path.dirname()
- 返回文件中目录名
path.dirname('http://localhost:4001/news/index.html') // http://localhost:4001/news
- windows 中
path.dirname('file:///D:/news/a.js'); // file:///D:/news
- windows 中
3.path.basename()
- 返回 path 的最后一部分,(第二个参数为可选的文件拓展名)
path.basename('http://localhost:4001/news/index.html') //index.html
- 第二个参数
path.basename('http://localhost:4001/news/index.html','.html') //index
- 第二个参数
4.path.extname()
- 返回路径中的扩展名,即 path 中文件的后缀名,如果没有则返回空字符串
path.extname('http://localhost:4001/news/index.html') //.html
- windows 中
path.extname('file:///D:/news/a.js') // .js
- windows 中
5.path.parse()
-
将字符串转换为对象
<!-- 返回值有以下属性 --> dir <string> root <string> base <string> name <string> ext <string>
path.parse('http://localhost:4001/news/index.html') //{ root: '', dir: 'http://localhost:4001/news', base: 'index.html', ext: '.html', name: 'index' }
6.path.format()
-
将 path 对象转换为字符串,与 path.parse()相反
- windows 中
var o = { root: '', dir: 'C:\\path\\dir', base: 'a.js', ext: '.js', name: 'a', }; var str = path.format(o); //C:\path\dir\a.js