开发者

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

In a Node.js module 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.js file.

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. As such, I think I need to know how to get the path of the current Node.js module which is executing.

Thanks.


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).

For example:

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

Just to save someone from a headache.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜