In node.js a variable/constant or a function you set within a file won’t necessarily be available for you to use on any other file of your choice. If we had two js files in our repository, app.js and utils.js we couldn’t use our functions from utils.js within app.js if we haven’t made them available.
This is where module exports can come in handy. Let’s have a look how to export a variable and then a function to our app.js file
1. Exporting a constant from another file to your app.js
Assuming you already have an app.js file in your project, we’ll need to create a new file and call it utils.js. Inside of it we will create a constant named firstName and set a value to it.
const firstName = 'Likii';
We could use console.log to make sure our firstName gets printed out once we run our app so we will write it up like this:
This still won’t do much for us because our firstName is not available to app.js file, so we’ll use module exports to help us here:
module.exports = firstName;
b.) In your app.js file (your main js file) declare a constant called ‘name’ which will ‘require’ our new file containing the firstName constant we set earlier.
const name = require('./utils.js');
And the last thing we need to do is use console to log this like this: