如何使用Node.js获取当前脚本的路径? [英] How do I get the path to the current script with Node.js?
问题描述
我如何在Node.js中获取脚本的路径?
How would I get the path to the script in Node.js?
我知道有process.cwd
,但这仅是指脚本被调用的目录,而不是脚本本身的目录.例如,假设我在/home/kyle/
中,然后运行以下命令:
I know there's process.cwd
, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/
and I run the following command:
node /home/kyle/some/dir/file.js
如果我呼叫process.cwd()
,则会得到/home/kyle/
,而不是/home/kyle/some/dir/
.有没有办法获取该目录?
If I call process.cwd()
, I get /home/kyle/
, not /home/kyle/some/dir/
. Is there a way to get that directory?
推荐答案
我在仔细阅读了文档后发现了它.我正在寻找的是 __filename
和 __dirname
模块级变量.
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
-
__filename
是当前模块的文件名.这是当前模块文件的解析绝对路径. (例如:/home/kyle/some/dir/file.js
) -
__dirname
是当前模块的目录名称. (例如:/home/kyle/some/dir
)
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
这篇关于如何使用Node.js获取当前脚本的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!