Node.js 中,__dirname 总是指向被执行 js 文件的绝对路径,./ 会返回你执行 node 命令的路径
path 模块提供了一些用于处理文件与目录的路径的实用工具,使用如下方式访问
const path = require('path');
1. path.join
const path1 = path.join(__dirname, '/foo');
const path2 = path.join(__dirname, './foo/bar');
const path3 = path.join('/foo', 'bar', '/baz/apple', 'aaa', '..');
const path4 = path.join('foo', 'bar', 'baz');
console.log(path1);
console.log(path2);
console.log(path3);
console.log(path4);
// 输出结果
/Users/xiao/work/test/foo
/Users/xiao/work/test/foo/bar
/foo/bar/baz/apple
foo/bar/baz
2. path.resolve
const path = require('path');
const path1 = path.resolve('/a/b', '/c/d');
// 结果: /c/d
const path2 = path.resolve('/a/b', 'c/d');
// 输出: /a/b/c/d
const path3 = path.resolve('/a/b', '../c/d');
// 输出: /a/c/d
const path4 = path.resolve('a', 'b');
// 输出: /Users/xiao/work/test/a/b
「@浪里淘沙的小法师」