简体   繁体   English

node.js 中的相对路径问题

[英]Relative path issue in node.js

在此处输入图片说明

Above is the directory structure.以上是目录结构。 I am trying to access the above highlighted file: DatabaseConnection using below code inside login_API.js我正在尝试访问上面突出显示的文件:DatabaseConnection using below code inside login_API.js

var connection = require("../../../../DatabaseConnection");

I am doing the same thing in many many other files.我在许多其他文件中做同样的事情。

Issue is: What will happen if the file path of DatabaseConnection is changes tomorrow.问题是:如果明天 DatabaseConnection 的文件路径发生变化会发生什么。 In that case I will have to rewrite the correct relative paths again in all the files.在这种情况下,我将不得不在所有文件中再次重写正确的相对路径。

Can you please suggest how can I change the above line of code to utilize it better?您能否建议我如何更改上述代码行以更好地利用它?

I tried to follow an another way as mentioned here: https://stackoverflow.com/a/26163910/726802我试图遵循这里提到的另一种方式: https : //stackoverflow.com/a/26163910/726802

But, failed to understand that how to use the below code in my case:但是,无法理解如何在我的情况下使用以下代码:

var myModule = require.main.require('./path/to/module');

您可以将DatabaseConnection.js放在node_modules ,然后以这种方式要求它:

var connection = require("DatabaseConnection");

With nodejs you can use __filename or __dirname.使用 nodejs,您可以使用 __filename 或 __dirname。 More information here, on the official site of Nodejs: https://nodejs.org/docs/latest/api/modules.html#modules_filename更多信息,请访问 Nodejs 官方网站: https ://nodejs.org/docs/latest/api/modules.html#modules_filename

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

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