I’m creating a program in
I originally had the entire program in one giant (~500 line) script file. Several people suggested I split it up into separate classes, where each class only has one ‘job’ to complete. I like this idea as it has helped me really streamline my code and make it more modular and manageable.
My issue is: How do I access these classes from a central file?
it into a variable, then access the script’s functions like so?
var class1 = require('./class1.js'); class1.function1(); // call the first function contained in class1.js
Is such a thing even possible? Again, totally new to this.
Problem courtesy of: Jascination
NodeJS supports CommonJS modules
. A CommonJS module provides three global variables: module
You can export your API by adding to the
these files just like other node modules (add
to indicate that it is relative to the current file), assign it to a variable and access the values you added to that files
// first-module.js exports.hello = 'world'; exports.num = 23; // main.js var first = require('./first-module'); console.log(first.hello); console.log(first.num);
Solution courtesy of: Daff