Node.js __filename 对象
Node.js 中的__filename返回所执行代码的文件名。它给出了代码文件的绝对路径。以下方法介绍了如何在 NodeJS 项目中实现__filename 。
句法:
console.log(__filename)
先决条件:
- Node.js 基础知识
- 已安装 Node.js(版本 12+)
- 已安装 NPM(版本 6+)
返回值:返回当前模块的绝对文件名。
示例 1:创建一个 JavaScript 文件index.js并记下以下代码:
index.js
// Node.js code to demonstrate the absolute
// file name of the current Module.
console.log("Filename of the current file is: ",
__filename);
index.js
// Node.js code to demonstrate the absolute
// file name of the current Module
console.log(__filename);
// To show to parts of file using filename.
const parts = __filename.split(/[\\/]/);
console.log( "This the all the parts "
+ "present in file :",parts);
使用以下命令运行index.js文件:
node index.js
输出:
Filename of the current file is:
C:\Users\Pallavi\Desktop\node_func\app.js
示例 2:
index.js
// Node.js code to demonstrate the absolute
// file name of the current Module
console.log(__filename);
// To show to parts of file using filename.
const parts = __filename.split(/[\\/]/);
console.log( "This the all the parts "
+ "present in file :",parts);
输出:
C:\Users\Pallavi\Desktop\node_func\app.js
This the all the parts present in file :
[ 'C:', 'Users', 'Pallavi', 'Desktop',
'node_func', 'app.js' ]
参考: https://nodejs.org/api/globals.html#globals_filename