[英]Node.js | Call function from original file in imported file
I recently tried to organize my code by exporting functions into different files, so my main file stays clean. 我最近尝试通过将函数导出到不同的文件中来组织代码,因此我的主文件保持干净。 To do so I imported the other js file in my main file with
为此,我将其他js文件导入了我的主文件中
const request = require('./request.js');
In "request.js" I used export
, so I can call the function in my main file. 在“ request.js”中,我使用了
export
,因此可以在主文件中调用该函数。 Is it is possible to call a function, that is defined in the main file, from the "request.js" file? 是否可以从“ request.js”文件调用主文件中定义的函数? Unfortunately I can't just return the information back to the main file, because I am using callbacks.
不幸的是,我不能仅仅将信息返回到主文件,因为我正在使用回调。
Yes it's possible. 是的,有可能。
You just need to export function from the main file and then import your main file inside request.js
: 您只需要从主文件中导出功能,然后将您的主文件导入
request.js
:
// main.js:
module.exports.someFunction = function() {
// Some code
};
const request = require('./request.js');
request.someRequestFunction();
// request.js
var main = require('./main.js');
module.exports = {
someRequestFunction: function() {
main.someFunction(); // Call function from main module
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.