To give a more detailed answer, there are a few ways of being able to do this. The first way to do this is to use module.exports with an object. This will allow you to import the module using require
(or, using a compiler like babel or webpack, import
), and you can call any function within the object. This is using the method of @MaxxiBoi's response.
// File 1
module.exports = {
"myFunction1": (arg1, arg2) => {
console.log("Function 1 with 2 args: "+ arg1 + " " + arg2);
},
"myFunction2": () => {
console.log("Function 2");
}
}
// File 2
const myModule = require("./file1.js");
myModule.myFunction1(null, "Hi"); // Logs "Function 1 with 2 args: null Hi"
myModule.myFunction2(); // Logs "Function 2"
While this can be useful in situations where you want to output more than one function, if you only want one function per module, I wouldn't do this.
The second method would be using module.exports with a variable or function, instead of an object. This can keep down clutter and make it easier to understand.
// File 1
module.exports = myFunction1(arg1, arg2) {
console.log("Function 1 with 2 args: " + arg1 + " " + arg2);
}
// File 2
const myFunction = require("./file1.js");
myFunction(null, "Hi"); // Logs "Function 1 with 2 args: null Hi"
Finally, there's another method of creating a constructor using either ES5 or ES6 (for this example I'm using ES6), which will allow you to be able to pass more variables into it that you can then reference within said class. In this example, I'm using a Discord.js client and getting the client's name from the constructor. Assume the client's name is "George".
// File 1
module.exports = class MyClass {
constructor(client) {
this.client = client;
}
myFunction1(myVar2) {
console.log("Function 1 with 2 args: " + this.client.user.username + " " + myVar2);
}
myFunction2() {
console.log("Function 2");
}
}
// File 2
const MyClass = require("./MyClass.js");
const myClassInstance = new MyClass(client);
myClassInstance.myFunction1("Hi"); // Logs "Function1 with 2 args: George Hi"
myClassInstance.myFunction2(); // Logs "Function 2"
In the end, it's all up to what you prefer and how you'd like to do it. Each method has their ups and downs. If you want to learn more about how I made all of these and how modules work in general, check out the Node.js docs explanation. To learn more about classes (the one used in the third module), check out the MDN documentation. Hope I was able to help and give you options. You may also want to take a look at this StackOverflow question, as it will solve your question about referencing a file in a different directory. Happy coding!