node 内置模块之 path

路径处理模块path

获取路径/文件名/拓展名

  • 获取路径:path.dirname(filepath)
  • 获取文件名:path.basename(filepath)
  • 获取后缀名:path.extname(filepath)
var path = require('path');
var filepath = '/tmp/demo/js/test.js';

// 输出:/tmp/demo/js
console.log( path.dirname(filepath) )
// 输出:test.js
console.log( path.basename(filepath) )
// 输出:test
console.log( path.basename(filepath, '.js') )
// 输出:.js
console.log(path.extname(filepath) )
// 输出:.
console.log( path.extname('index.') )

路径组合

  • path.join([...paths])
  • path.resolve([...paths])

1. path.resolve()

  • 将路径或者路径片段的序列解析为绝对路径
  • 返回的路径是从右往左处理,后面的每个 path 被解析,直到构造出完成的绝对路径
const path = require('path');

let arr1 = ['/foo1/foo2', 'dselegent', 'foo3'];
let result1 = path.resolve(...arr1);
console.log(result1); // 打印结果:/foo1/foo2/dselegent/foo3

let arr2 = ['/foo1/foo2', '/dselegent', 'foo3'];
let result2 = path.resolve(...arr2);
console.log(result2); // 打印结果:/dselegent/foo3
const path = require('path')

// 当前工作路径为:/Users/abc/Document/examples/path

// 输出:/Users/abc/Document/examples/path
console.log( path.resolve('') )
console.log( path.resolve('.') )

// 输出:/a/b/c
console.log( path.resolve('/a/b', './c') )
// 输出:/a/c
console.log( path.resolve('/a/b', '../c') )
//输出:c
console.log( path.resolve('/a/b', '/c') )

2. path.join()
用于路径拼接,使用特定的分界符将所有给定的 path 片段连接在一起,然后规范化生成的路径

const path = require('path)

// 当前工作路径为:/Users/abc/Document/examples/path

输出:/Users/abc/Document/examples/path/app.js
console.log( path.join(__dirname,'./app.js') )

输出:/a/b/c
console.log( path.join('/a', 'b', './c') )
输出:/a/c
console.log( path.join('/a', 'b', '../c') )

path.resolve 和 path.join 的区别

  1. 如果 dirname 是以 ./、../ 不加 / 开头的话,那么 resolve 会找到磁盘下的根目录
const path = require("path");
 
var dirname = '../User/Desktop';
var basename = 'abc.txt';
 
path.join(dirname, basename);  // ../User/Desktop/abc.txt
 
path.resolve(dirname, basename);  // /Users/Desktop/node/User/Desktop/abc.txt
  1. 如果 basename 是以 / 开头的,那么 resolve 就会直接返回 basename
const path = require("path");
 
var dirname = '/User/Desktop';
var basename = '/abc.txt';
 
path.join(dirname, basename);  // /User/Desktop/abc.txt
 
path.resolve(dirname, basename);  // /abc.txt

几个常见路径

  • __dirname:表示当前执行文件所在的完整目录
  • __filename:表示当前执行文件的完整目录 + 执行文件名
  • process.cwd():表示当前执行 Node 命令时的目录
// 输出:D:\node\node_practice\02_地址path
console.log(__dirname);

// 输出:D:\node\node_practice\02_地址path\index.js
console.log(__filename);

// 输出:D:\node\node_practice
console.log(process.cwd());
posted @ 2023-05-18 10:28  超重了  阅读(95)  评论(0编辑  收藏  举报