Tags

Node.js

Exporting Multiple Items From A Module

Last week we created our first module count.js for counting items in an array. To make it a module, all we did was to assign the main function to module.exports , so that it is accessible to the main application that requires this module. So considering the below code:

var count = function (arr) {
// Get the length of the array.
var len = arr.length;
// Return the string that conveys the number of elements.
return “There are ” + len + ” items in this array.”;
};
module.exports = count;

We can use the count wherever we need by simply requiring it the below way:

var count = require(“./count”);

Because we have stored that in the count variable. But what if we want to return more than one function? We can’t be writing new modules for every single function we create. What if this was not just a counting module, but it has a whole lot of utility functions? Let’s imagine a utility module, where there are lots of utility functions. For example, a simple mathematical utility module. It might have functions like add , subtract , multiply , divide , etc. and we can’t keep creating modules for each function.

The first thing I am going to do is to rename the count.js into utils.js , as in utilities. I am also going to update the requiring declaration to include utils and not count .

// We don’t need a .js as it automatically finds the JavaScript files to require.
var utils = require(“./utils”);
console.log(count([“Praveen”, “Purush”, “Science”, “Kittens”]));

More Behaviours

Currently, we need to handle when there’s more than one function we need to expose. You cannot send more than one variable in a single definition right? So, to make something like that, in our utils.js , I am going to create another function called add(, which is going to take two numbers and returns a string that is going to say, “The sum of the two numbers is (sum).”

var add = function (a, b) {
return “The sum of the two numbers is ” + (a + b) + “.”;
};

Variables Are Allowed Too!

I am also going to add another variable, say pi and then assign it to a floated variable. I am aware that we can get it from the Math object in JavaScript, but just for demonstrating, how to expose different types of variables and parts of the code, I am going to add this too:

var pi = 22.0 / 7.0;

I have given 22.0 and 7.0 like that because I don’t want the output to be truncated and I make sure JavaScript is calculating the values in decimals and not as integers. Now the whole file looks something like this:

var count = function (arr) {
// Get the length of the array.
var len = arr.length;
// Return the string that conveys the number of elements.
return “There are ” + len + ” items in this array.”;
};
var add = function (a, b) {
return “The sum of the two numbers is ” + (a + b) + “.”;
};
var pi = 22.0 / 7.0;
module.exports = count;

Changing the App.js to Suit New Naming

Now, when I require the module this way:

var count = require(“./utils”);

I want to make sure that all the three elements – count , add , and pi should be accessible to me using utils , when we require this module. So let’s now dive deep into how we will be doing it.

module.exports = count;

We had given the above way to expose our count variable. To be honest, module.exports is just an empty object, to begin with. So what we can essentially do is to add on more properties to this object. The above code can be rewritten as:

module.exports.count = count;

Now the count property of this module.exports object will be containing the function definition of our counting function. And therefore, in this way, we can add other properties for including all other functions in our utility module. Copying and pasting, we’ll be getting something like:

module.exports.count = count;
module.exports.add = add;
module.exports.pi = pi;

We are now exposing all the different functions that we have written in this utility file. Now all these functions and variables are made available outside this module and we can use them wherever we require this module. This time, we’ll need to change a few more things in our main app.js file.

Updating the Function Call

I am going to first change the variable name of the inclusion to utils , as this doesn’t only contain the count , but everything else too.
 

var utils = require(“./utils”);

And the other part that needs changing is the function call. It’s going to be updated as instead of saying count , it’s going to be utils.count :

console.log(utils.count([“Praveen”, “Purush”, “Science”, “Kittens”]))

This is because, utils is just another object, which contains all the functions and variables of our module file. Let’s try running this file again with the complete code below:

// We don’t need a .js as it automatically finds the JavaScript files to require.
var utils = require(“./utils”);
console.log(utils.count([“Praveen”, “Purush”, “Science”, “Kittens”]));

And see if it works:

praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ node app

There are 4 items in this array. 

Woohoo! It works. Now let’s try calling the other functions too. Add another console.log() to the last line:

// We don’t need a .js as it automatically finds the JavaScript files to require.
var utils = require(“./utils”);
console.log(utils.count([“Praveen”, “Purush”, “Science”, “Kittens”]));
console.log(utils.add(6, 9));

Once we save this and run, we’ll get the following output:

praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ node app
There are 4 items in this array.
The sum of the two numbers is 15.

Including Other Objects in the Function Call

We get the first output, which we saw in our previous one. Now along with it, there’s the sum of two numbers, that follows our first output. That was awesome. We still have the other variable pi and we can also include it inside the utils . We just need to prefix it with utils. and we are good to go.

// We don’t need a .js as it automatically finds the JavaScript files to require.
var utils = require(“./utils”);
console.log(utils.count([“Praveen”, “Purush”, “Science”, “Kittens”]));
console.log(utils.add(5, utils.pi));

Now saving the above code and running it gives you the following output:

praveen@PRAVEEN.SCIENCE MINGW64 ~/NodeJS
$ node app
There are 4 items in this array.
The sum of the two numbers is 8.142.

The last statement we received is nothing but the sum of 3.142, which is the value of pi added with the 5 . Now we have exported a lot of things from this single module. The next article, we’ll be looking at what are all the best practices of using module pattern and how can we code better. Hope it was interesting and useful. Until then, it’s bye from Praveen Kumar!


Thanks to Praveen Kumar for being our guest writer this week.

Who Are Ronald James?

We are a leading niche digital & tech recruitment specialist for the North East of England. We Specialise in the acquisition of high-performing technology talent across a variety of IT sectors including Digital & Technology Software Development.

Our ultimate goal is to make a positive impact on every client and candidate we serve - from the initial call and introduction, right up to the final delivery, we want our clients and candidates to feel they have had a beneficial and productive experience.

Contact our Team

If you’re looking to start your journey in sourcing talent or find your dream job, you’ll need a passionate, motivated team of experts to guide you. Check out our Jobs page for open vacancies. If interested, contact us or call 0191 620 0123 for a quick chat with our team.

Let's be Friends!

Follow us on our blog, Facebook, LinkedIn, Twitter or Instagram to follow industry news, events, success stories and new blogs releases.

 

Back to Blog

</Follow Us>