Node.js之path模块

Node.js 之 Path模块

//引用该模块
var path = require("path");

1. path.normalize 路径解析,得到规范化的路径格式

/**
* 对window系统,目录分隔为'\',
* 对于UNIX系统,分隔符为'/',
* 针对'..'返回上一级;
* /与\\都被统一转换
* path.normalize(p);
*/

var myPath = path.normalize(__dirname + '/test/a//b//../c/utilyou.mp3');
console.log(myPath); //windows: E:\workspace\NodeJS\app\fs\test\a\c\utilyou.mp3

2. path.join 路径结合、合并,路径最后不会带目录分隔符

/**
* path.join([path1],[path2]..[pathn]);
* [path1] 路径或表示目录的字符,
*/

var path1 = 'path1',
    path2 = 'path2//pp\\',
    path3 = '../path3';

var myPath = path.join(path1, path2, path3);
console.log(myPath); //path1\path2\path3

// 或者如下实例:
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// throws 'TypeError: Path must be a string. Received {}'

3. path.resolve 获取绝对路径

//path.resolve(path1, [path2]..[pathn]);

//以应用程序为起点,根据参数字符串解析出一个绝对路径

/**
* path 必须至少一个路径字符串值
* [pathn] 可选路径字符串
*/

var myPath = path.resolve('path1', 'path2', 'a/b\\c/');
console.log(myPath);//E:\workspace\NodeJS\path1\path2\a\b\c

// 官网api: 
path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// if the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

4. path.sep属性 统一不同系统的分隔路劲符

  • \ on Windows
  • / on POSIX
/** 
 * 返回操作系统中文件分隔符; window是'\\', Unix是'/'
 */
 
// for unix:
 'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']

// for windows:
'foo\\bar\\baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']