文件操作在 Node.js 编程中使用频率很高,路径处理是文件操作的前提,Node.js 通过 path 模块提供了路径处理的基础 API
Window 和 POSIX 对比
Path 模块在不同操作系统处理会有所差异,路径风格和操作系统不一致会出现意外的结果
在 Windows 操作系统上运行, path 模块会假定正被使用的是 Windows 风格的路径C:\\temp\\myfile.html
在 POSIX 操作系统会默认使用 POSIX 的路径风格/temp/myfile.html
POSIX,Portable Operating System Interface,是 UNIX 系统的一个设计标准,很多类 UNIX 系统也在支持兼容这个标准,如 Linux 和 Mac OS 所基于的 FreeBSD
Path 的方法
如果希望在不同操作系统都返回指定系统的结果,需要使用
path.win32.method
path.posix.method
basename(path)
path.basename()
方法用于返回一个路径的 basename
const path = require('path');
path.posix.basename('C:\\temp\\myfile.html') // C:\temp\myfile.html
path.win32.basename('C:\\temp\\myfile.html') // myfile.html
parse(path)
parse.parse()
方法用来解析文件路径,返回 对应的元信息对象
const path = require('path');
// {
// root: '',
// dir: '',
// base: 'C:\\temp\\myfile.html',
// ext: '.html',
// name: 'C:\\temp\\myfile'
// }
const a = path.posix.parse('C:\\temp\\myfile.html')
// {
// root: 'C:\\',
// dir: 'C:\\temp',
// base: 'myfile.html',
// ext: '.html',
// name: 'myfile'
// }
const b = path.win32.parse('C:\\temp\\myfile.html')
format(parseObject)
path.format()
方法从对象返回路径字符串,是 path.parse
的反操作
const path = require('path');
// C:\temp\myfile.html
path.posix.format({
root: '',
dir: '',
base: 'C:\\temp\\myfile.html',
ext: '.html',
name: 'C:\\temp\\myfile'
})
// C:\temp\myfile.html
path.win32.format({
root: 'C:\\',
dir: 'C:\\temp',
base: 'myfile.html',
ext: '.html',
name: 'myfile'
})
normalize(path)
path.normalize()
方法规范化给定的 path,解析 ..
和 .
const path = require('path');
path.posix.normalize('/foo/bar//baz/asdf/quux/..'); // 返回:/foo/bar/baz/asdf
path.win32.normalize('/foo/bar//baz/asdf/quux/..'); // 返回:\foo\bar\baz\asdf
join([…paths])
path.join()
使用操作系统规定的分隔符将参数中的 path 片段连接,并且规范化
const path = require('path');
path.posix.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // 返回:/foo/bar/baz/asdf
path.win32.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // 返回:\foo\bar\baz\asdf
relative(from, to)
path.relative()
方法根据当前工作目录返回 from 到 to 的相对路径
const path = require('path');
path.posix.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') // 返回:../../impl/bbb
path.win32.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') // 返回:..\..\impl\bbb
resolve([…paths])
path.resolve()
方法将路径或路径片段的序列解析为绝对路径
const path = require('path');
path.posix.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// 如果当前的工作目录是 D:/gitRepository/nodeLearn/,
// 则返回 D:/gitRepository/nodeLearn/wwwroot/static_files/gif/image.gif
path.win32.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// 如果当前的工作目录是 D:\gitRepository\nodeLearn\,
// 则返回 D:\gitRepository\nodeLearn\wwwroot\static_files\gif\image.gif
获取基本信息
path.delimiter
: 返回操作系统路径界定符,Windows 返回;
POSIX 返回:
path.dirname
: 返回文件目录名path.sep
: 返回路径分隔符,Windows 返回\
POSIX 返回/
path.extname(path)
: 返回路径的拓展名(jquery.min.js 拓展名是 .js)path.isAbsolute(path)
: 检测路径是否是绝对路径