felenwe 2016-01-06 1758浏览量
用过python的童鞋一定知道python有一个自带模块os.path,os.path集成了很多关于路径的操作,非常好用。
Node.js的path模块类似于python的os.path,尽管功能没有那么丰富。
来看看path有哪些功能
var path = require('path');
var path_str = '/home/lee/works/nodejs/study12/index.html';
console.log('文件名带后缀:'+path.basename(path_str));
console.log('文件名不带后缀:'+path.basename(path_str, '.html'));
console.log(path.delimiter); //一般linux是‘:’,windows是‘;’
console.log(process.env.PATH); //打印环境变量path
console.log(process.env.PATH.split(path.delimiter)) //用path.delimiter分割
console.log(path.sep); // ‘/’或‘\\’
console.log(path_str.split(path.sep)); // [ '', 'home', 'lee', 'works', 'nodejs', 'study12', 'index.html' ]
console.log(path.dirname(path_str)); // /home/lee/works/nodejs/study12
console.log(path.extname(path_str)); //.html
console.log(path.extname('index.html.bak')); //.bak
path_format = path.format({
root : "/",
dir : "/home/user/dir",
base : "file.txt",
ext : ".txt",
name : "file"
});
console.log(path_format); // '/home/user/dir/file.txt'
console.log(path.isAbsolute(path_str)); //true
console.log(path.isAbsolute('/foo/bar')); // true
console.log(path.isAbsolute('/baz/..') ); // true
console.log(path.isAbsolute('qux/')); // false
console.log(path.isAbsolute('.')); // false
console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')); // '/foo/bar/baz/asdf'
console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux')); // '/foo/bar/baz/asdf/quux'
console.log(path.normalize('/foo/bar//baz/asdf/quux/..')); // '/foo/bar/baz/asdf'
var path_parsed = path.parse(path_str);
console.log(path_parsed);
/*
{ root: '/',
dir: '/home/lee/works/nodejs/study12',
base: 'index.html',
ext: '.html',
name: 'index' }
*/
console.log(path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'));
// '../../impl/bbb'
console.log(path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'));
/*
相当于执行了
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd
最后返回当前路径
*/
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
集结各类场景实战经验,助你开发运维畅行无忧