node环境下process.cwd()与__dirname的区别

261 阅读1分钟

结论

场景:node环境下运行一个js脚本:node xxx/xxx/xxx/脚本名.js

  • __dirnamenode命令要执行的脚本在计算机中的绝对位置,即脚本名.js脚本文件所在的位置(字面理解:dirname:目录名,因为__dirname写在js文件中,所以就代表了当前js文件所在的目录名)
  • process.cwd():执行node命令所在计算机中的绝对位置,即node xxx/脚本名.js这个命令是在哪执行的(字面理解:process即当前进程,也就是node命令的执行;cwd即current work dir,当前工作目录)

举例

随便建个test文件夹,内部结构如下:

test/
└── dir_top/
    └── dir_mid/
        └──test.js

test.js

console.log(__dirname);
​
console.log(process.cwd());

test文件夹内打开终端,即当前位置/xxx/xxx/test

执行命令:

node ./dir_top/dir_mid/test.js

结果:

console.log(__dirname); // 输出:/xxx/.../test/dir_top/dir_mid,即脚本文件test.js所在的位置console.log(process.cwd()); // 输出:/xxx/.../test,即node命令执行的位置