Better way to export functions in node.js

avatar

Better ways to export functions

While creating a bot for Splinterlands (Excuse me), my javaScript code was very cumbersome in the initial stages(not that it is clear now). At some point, I discovered a proper way to communicate between different modules by exporting functions. So, I created a helper file that contains useful functions, to be used throughout the project.

Previously ...

To use a function from a module, it needs to be exported.

/** file.js */
const helloWorld=()=>console.log('Hello World');
/** rest of the file */

module.exports = { helloWorld }

Now the helloWorld function can be used by other files. If we want any other function to export, we need to declare it and add it to the module.exports variable.

Now...

To automatically export a function, we can attach it to a variable and export that variable from the module.

/** file.js */
const helper = {}
helper.helloWorld=()=>console.log('Hello World');

const hi=(place,name)=>console.log(`Welcome to ${place}, ...${name}`);
helper.hiWorld=name=>hi('World');
/** rest of the file */

module.exports = { helper }
/** otherFile.js */
const { helper } = require('./file')

helper.hiWorld('ruby') //Welcome to World, ...ruby
helper.hi('Home','ruby')//Error!! hi function not available

As you can see, the hi function is a local function in file.js, but hiWorld is available through the helper variable that stores the function and is thus available for other files. Now, I can attach required functions and variables to the helper variables, without worrying if I exported from the current module.

Further

modules
my helper.js file

Thanks



0
0
0.000
1 comments