gpt4 book ai didi

node.js - 访问另一个模块中的函数。导出到单独的文件中

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:12 25 4
gpt4 key购买 nike

我有几个 javascript 文件,其中包含我的 Node 应用程序的不同部分。使用以下逻辑需要它们。我想从 file2.js 访问一个 file1.js 中的函数,但到目前为止还没有成功。任何帮助将不胜感激,谢谢。

app.js:这是我启动服务器并包含所有快速路由的文件。

require(path_to_file+'/'+file_name)(app, mongoose_database, config_file);  //Require a bunch fo files here in a loop.

file1.js:这是使用上述代码所需的示例文件。

module.exports = function(app, db, conf){
function test() { //Some function in a file being exported.
console.log("YAY");
}
}

file2.js:这是使用上述代码所需的另一个文件。我想从该文件 (file2.js) 中访问 file1.js 中的函数。

module.exports = function(app, db, conf){
function performTest() { //Some function in a file being exported.
test();
}
}

最佳答案

文件1.js

module.exports = function(app, db, conf){
return function test() {
console.log("YAY");
}
}

请注意,您需要返回该函数。

file2.js

module.exports = function(app, db, conf){
return function performTest() {
var test = require('./file1')(app, db, conf);
test();
}
}

(其他一些文件)

var test = require('./file2')(app, db, conf);
test();

require('./file2')(app, db, conf)();

关于node.js - 访问另一个模块中的函数。导出到单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13366824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com