---
title: "使用NodeJS的Path对象进行路径操作"
author: "wenson"
date: "2014-04-30T18:52:00Z"
tags: []
categories: ["编程语言"]
slug: "nodejs-path"
draft: false
lastmod: "2014-04-30T18:52:00Z"
id: 2058998
url: "https://wenson.iteye.com/blog/2058998"
---

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

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. var path = require('path');

比较实用的方法： 

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

示例： 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. path.normalize('/foo/bar//baz/asdf/quux/..');
2. // returns
3. '/foo/bar/baz/asdf'

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

示例： 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. path.join('///foo', 'bar', '//baz/asdf', 'quux', '..');
2. // returns
3. '/foo/bar/baz/asdf'

**路径寻航 path.resolve(\[from ...], to)**   
特点：相当于不断的调用系统的cd命令 

示例： 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. 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代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')
2. // returns
3. '..\\\\..\\\\impl\\\\bbb'
4. path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
5. // returns
6. '../../impl/bbb'

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

示例： 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. path.dirname('/foo/bar/baz/asdf/quux')
2. // returns
3. '/foo/bar/baz/asdf'

**文件名称 path.basename(p, \[ext])**   
特点：返回指定的文件名，返回结果可排除\[ext]后缀字符串 

示例： 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. path.basename('/foo/bar/baz/asdf/quux.html')
2. // returns
3. 'quux.html'
4. path.basename('/foo/bar/baz/asdf/quux.html', '.html')
5. // returns
6. 'quux'

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

示例： 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

1. path.extname('index.html')
2. // returns
3. '.html'
4. path.extname('index.')
5. // returns
6. '.'
7. path.extname('index')
8. // returns
9. ''

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

示例：   
linux: 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

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

window: 

Js代码  [![收藏代码](http://haiyupeter.iteye.com/images/icon_star.png)]()

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

转自：http://haiyupeter.iteye.com/blog/1733260