javascript 在 Node.js 中,我如何知道 `this` 模块的路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5215871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:23:55  来源:igfitidea点击:

In Node.js how can I tell the path of `this` module?

javascriptpathnode.js

提问by Chris W.

In a Node.js module I'm writing I would like to open a file--i.e, with fs.readFile()--that is contained in the same directory as my module. By which I mean it is in the same directory as the ./node_modules/<module_name>/index.jsfile.

在我正在编写的 Node.js 模块中,我想打开一个文件——即,它与fs.readFile()我的模块包含在同一目录中。我的意思是它与./node_modules/<module_name>/index.js文件位于同一目录中。

It looks like all relative path operations which are performed by the fsmodule take place relative to the directory in which Node.js is started. As such, I think I need to know how to get the path of the current Node.js module which is executing.

看起来fs模块执行的所有相对路径操作都是相对于 Node.js 启动的目录进行的。因此,我想我需要知道如何获取当前正在执行的 Node.js 模块的路径。

Thanks.

谢谢。

回答by Afshin Mehrabani

As david van brink mentioned in the comments, the correct solution is to use __dirname. This global variable will return the path of the currently executing script (i.e. you might need to use ../to reach the root of your module).

正如评论中提到的 david van brink,正确的解决方案是使用__dirname. 该全局变量将返回当前正在执行的脚本的路径(即您可能需要使用它../来访问模块的根目录)。

For example:

例如:

var path = require("path");
require(path.join(__dirname, '/models'));

Just to save someone from a headache.

只是为了让某人免于头痛。