Path模块

路径Path

  • 引入
/*
* 路径模块 path
* */
const path = require('path');

//获取路径最后部分
// console.log(path.basename('/foo/bar/baz/asdf/quux.html'));
// console.log(path.basename('/foo/bar/baz/asdf/quux.html', '.html'));


//获取路径
// console.log(__dirname);
// console.log(path.dirname(__dirname));

//获取后缀名
// console.log(path.extname('index.html'));
// // Returns: '.html'
//
// console.log(path.extname('index.coffee.md'));
// // Returns: '.md'
//
// console.log(path.extname('index.'));
// // Returns: '.'
//
// console.log(path.extname('index'));
// // Returns: ''
//
// console.log(path.extname('.index'));
// // Returns: ''
//
// console.log(path.extname('.index.md'));
// // Returns: '.md'

//路径的格式化处理
//path.format()  对象转为字符串
//path.parse()   字符串转为对象
//str->obj
let obj = path.parse(__filename);
console.log(obj);

/*
* {
  root: 'D:\\',
  dir: 'D:\\workspace\\nodejs\\web\\nodejs\\03.node基础\\0301.node基础',
  base: '02.js',
  ext: '.js',
  name: '02'
}
*/

let objpath = {
    root: 'D:\\',
    dir: 'D:\\workspace\\nodejs\\web\\nodejs\\03.node基础\\0301.node基础',
    base: '02.js',
    ext: '.js',
    name: '02'
};

//obj -> str
let strpath = path.format(objpath);
console.log(strpath);


//isAbsolute 绝对路径
console.log(path.isAbsolute('/foo/bar'));
console.log(path.isAbsolute("//server"));

//join 链接路径
// ..表示上层路径
console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '../../'));

//normallize规范化路径
console.log(path.normalize('/foo/bar//baz/asdf/quux/..'));
console.log(path.normalize('C:\\temp\\\\foo\\bar\\..\\'));

//relative计算相对路径
console.log(path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'));
console.log(path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'));

//resolve解析路径
console.log(path.resolve('/foo/bar', './baz'));
console.log(path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'));

//delimiter路径分隔符
//sep 环境变量分隔符
console.log(path.delimiter);   //windows ; linux :
console.log(path.sep);  //windows \ linux /

console.log(process.env.PATH.split(path.delimiter));
console.log('foo\\bar\\baz'.split(path.sep));
posted @ 2020-09-28 14:07  mrtransition  阅读(158)  评论(0)    收藏  举报