I have several javascript files that contain different parts of my node application. They are required using the logic below. I want to access a function in one file1.js from file2.js, but have had little success so far. Any help would be appreciated, thanks.
app.js: This is the file where I start my server and include all the express routes.
require(path_to_file+'/'+file_name)(app, mongoose_database, config_file); //Require a bunch fo files here in a loop.
file1.js: This is an example file that is required using the code above.
module.exports = function(app, db, conf){
function test() { //Some function in a file being exported.
console.log("YAY");
}
}
file2.js: This is another file required using the code above. I want to access a function in file1.js from within this file (file2.js).
module.exports = function(app, db, conf){
function performTest() { //Some function in a file being exported.
test();
}
}
module.exports = function(app, db, conf){
return function test() {
console.log("YAY");
}
}
Note you need to return the function.
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();
or
require('./file2')(app, db, conf)();
The function you have right now in file1 is scoped only to the function within the exports. Instead, you want to export an object with each function being a member of that object.
//file1.js
module.exports = {
test: function () {
}
};
//file2.js:
var file1 = require('./file1.js');
module.exports = {
performTest: function () {
file1.test();
}
}