问题描述
如何在 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 获取当前脚本的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!