fenghzy 发表于 2017-2-22 08:52:35

使用NodeJS的Path对象进行路径操作

NodeJS中的Path对象,用于处理目录的对象,提高开发效率。 
用NodeJS的Path命令,与使用Linux下的shell脚本命令相似。 
引入path对象 
Js代码  


[*]var path = require('path');  


比较实用的方法: 

格式化路径  path.normalize(p) 
特点:将不符合规范的路径格式化,简化开发人员中处理各种复杂的路径判断 

示例: 
Js代码  


[*]path.normalize('/foo/bar//baz/asdf/quux/..');  
[*]// returns   
[*]'/foo/bar/baz/asdf'  



路径联合 path.join(, , [...]) 
特点:将所有名称用path.seq串联起来,然后用normailze格式化 

示例: 
Js代码  


[*]path.join('///foo', 'bar', '//baz/asdf', 'quux', '..');  
[*]// returns   
[*]'/foo/bar/baz/asdf'  



路径寻航 path.resolve(, to) 
特点:相当于不断的调用系统的cd命令 

示例: 
Js代码  


[*]path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')  


相当于: 
cd foo/bar 
cd /tmp/file/ 
cd .. 
cd a/../subfile 
pwd 

相对路径 path.relative(from, to) 
特点:返回某个路径下相对于另一个路径的相对位置串,相当于:path.resolve(from, path.relative(from, to)) == path.resolve(to) 

示例: 
Js代码  


[*]path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')  
[*]// returns  
[*]'..\\..\\impl\\bbb'  
[*]  
[*]path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')  
[*]// returns  
[*]'../../impl/bbb'  



文件夹名称 path.dirname(p) 
特点:返回路径的所在的文件夹名称 

示例: 
Js代码  


[*]path.dirname('/foo/bar/baz/asdf/quux')  
[*]// returns  
[*]'/foo/bar/baz/asdf'  



文件名称 path.basename(p, ) 
特点:返回指定的文件名,返回结果可排除后缀字符串 

示例: 
Js代码  


[*]path.basename('/foo/bar/baz/asdf/quux.html')  
[*]// returns  
[*]'quux.html'  
[*]  
[*]path.basename('/foo/bar/baz/asdf/quux.html', '.html')  
[*]// returns  
[*]'quux'  



扩展名称 path.extname(p) 
特点:返回指定文件名的扩展名称 

示例: 
Js代码  


[*]path.extname('index.html')  
[*]// returns  
[*]'.html'  
[*]  
[*]path.extname('index.')  
[*]// returns  
[*]'.'  
[*]  
[*]path.extname('index')  
[*]// returns  
[*]''  



路径分隔符 path.sep 
特点:获取文件路径的分隔符,主要是与操作系统相关 

示例: 
linux: 
Js代码  


[*]'foo/bar/baz'.split(path.sep)  
[*]// returns  
[*]['foo', 'bar', 'baz']  


window: 
Js代码  


[*]'foo\\bar\\baz'.split(path.sep)  
[*]// returns  
[*]['foo', 'bar', 'baz']  


  转自:http://haiyupeter.iteye.com/blog/1733260
页: [1]
查看完整版本: 使用NodeJS的Path对象进行路径操作