一、__dirname 的介绍
1、解释说明:__dirname 是指获取当前文件在当前项目中的准确路径
2、使用方式:一般结合 node 的内置库 path.resolve 来使用,例:
const path = require("path");
const currentFilePath = path.resolve(__dirname, "index.js");
二、为什么建议使用 __dirname 不建议使用 “.”代替?
1、使用“.”的方式和现象如下:
示例代码:
const path = require("path");
console.log("使用“.”号的:", path.resolve(".", "index.js"));
执行结果:

执行结果说明:
使用“.”去拿当前index.js 文件的路径不在bin目录下,而是在当前项目路径下,这个路径严格来说是不对的,因为当前index.js 文件在bin目录下面;而且使用“.”会随着当前文件的深度变化而变化;
2、使用__dirname的方式和现象如下:
示例代码:
#! /usr/bin/env node
console.log("welcome to cli file");
console.log("===================================");
const path = require('path');
console.log("__dirname:", path.resolve(__dirname, 'index.js'));
console.log("相对路径.:",path.resolve(".", "index.js"));
// console.log("__filename:", __filename);
执行结果:

执行结果说明:
从上述执行结果中可以看出,使用 __dirname的模式,它拿到的才是当前文件的具体的真实的路径,而且不会随着当前文件的路径深度而发生变化;
3、总结说明:
根据上述的示例可以看出来__dirname 和 “.” 的差异,因此,如果需要拿到当前文件的绝对路径,建议使用 path.resolve(__dirname, "index.js")的模式去拿;
三、__filename 的介绍
解释说明:获取当前文件的完整路径和文件名称;
示例代码:
#! /usr/bin/env node
console.log("welcome to cli file");
console.log("===================================");
const path = require('path');
console.log("__dirname:", path.resolve(__dirname, 'index.js'));
console.log("相对路径.:",path.resolve(".", "index.js"));
console.log("__filename:", __filename);
执行结果:

3721

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



