在Node.js中,如何判断`this`模块的路径? [英] In Node.js how can I tell the path of `this` module?

查看:85
本文介绍了在Node.js中,如何判断`this`模块的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.js file.

看起来所有由 fs 模块执行的相对路径操作都是相对于Node.js启动的目录进行的。因此,我想我需要知道如何获取正在执行的当前Node.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. As such, I think I need to know how to get the path of the current Node.js module which is executing.

谢谢。

推荐答案

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

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

例如:

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

只是为了避免让人头疼。

Just to save someone from a headache.

这篇关于在Node.js中,如何判断`this`模块的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆