简体   繁体   English

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

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

In a Node.js module I would like to open a file--ie, with fs.readFile() --that is contained in the same directory as my module.在 Node.js 模块中,我想打开一个文件——即,使用fs.readFile() ——它与我的模块包含在同一目录中。 By which I mean it is in the same directory as the ./node_modules/<module_name>/index.js file.我的意思是它与./node_modules/<module_name>/index.js文件位于同一目录中。

It looks like all relative path operations which are performed by the fs module take place relative to the directory in which Node.js is started.看起来fs模块执行的所有相对路径操作都是相对于 Node.js 启动的目录进行的。 As such, I think I need to know how to get the path of the current Node.js module which is executing.因此,我想我需要知道如何获取当前正在执行的 Node.js 模块的路径。

Thanks.谢谢。

As david van brink mentioned in the comments, the correct solution is to use __dirname .正如评论中提到的 david van __dirname ,正确的解决方案是使用__dirname This global variable will return the path of the currently executing script (ie you might need to use ../ to reach the root of your module).该全局变量将返回当前正在执行的脚本的路径(即您可能需要使用../来访问模块的根目录)。

For example:例如:

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

Just to save someone from a headache.只是为了让某人免于头痛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM