path模块-提供用于处理文件路径和目录路径的实用工具
//引入模块
var path = require('path');
http://localhost:3000/a/b/c/d.html
1.path.join(); //拼接路径 根据系统的不同 用"/“或”"
console.log(path.join('/a', '/b', '/c'))
console.log(path.join("/temp", 'node', '/js/test.js')) //\temp\node\js\test.js
console.log(path.join("/temp", 'node', '/js/test.js/', '..')) //\temp\node\js
2.path.extname(); 获取路径扩展名
console.log(path.extname('index.html')) //.html
console.log(path.extname('index.coffee.md')) //.md
console.log(path.extname('html.')) // .
console.log(path.extname('.html')) // 空字符串
console.log(path.extname('html')) // 空字符串
console.log(path.extname('.')) // 空字符串
3.path.dirname() 返回路径中代表文件夹的部分
console.log(path.dirname("/node/base/path/test.js")) // node/base/path
console.log(path.dirname("/a/b/c/d")); // /a/b/c
console.log(path.dirname('/foo/bar/baz/asdf/quus')) // /foo/bar/baz/asdf
4.path.basename() 返回路径中的最后一部分
console.log(path.basename("/node/base/path/test.js")) //test.js
console.log(path.basename("/node/base/path/test")) //test
5.path.parse() 返回路径字符串的对象。字符串转对象
console.log(path.parse('C:\\path\\dir\\file.txt'))
{ root: 'C:\\',
dir: 'C:\\path\\dir',
base: 'file.txt',
ext: '.txt',
name: 'file' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
("" 行中的所有空格都应该被忽略,它们纯粹是为了格式化)
6.path.format() //从对象中返回路径字符串,和 path.parse 相反。
console.log(path.format({
root: '/ignored',
dir: '/home/user/dir',
base: 'file.txt'
})) //home/user/dir/file.txt
console.log(path.format({
root: 'C://',
base: 'file',
ext: '.html'
})) //C://file
7.path.relative()//绝对路径转为相对路径
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); //"../../impl/bbb"
8.path.resolve() 相对路径转化绝对路径
console.log(path.resolve('./')) //c:\Users\86152\Desktop\1709C\day10
9.path.normalize() //规范化路径 并解析 ‘…’ 和 ‘.’ 片段
本文深入探讨了Node.js中path模块的功能与使用方法,包括路径拼接、扩展名获取、路径解析与格式化、路径规范化等核心操作。通过具体实例展示了如何在不同场景下运用这些工具,帮助开发者更高效地进行文件路径处理。
1365

被折叠的 条评论
为什么被折叠?



