The require function
What if we want to modularize our code. To split our code into separate files, export them and then import them where we want to use them further?
We have seen this concept before with React, right? The answer is yes! The concept is the same, the only difference is the execution context. Now because we are not inside a browser, the way we export and import things change.
Node.js offers a native functionality for this and the ES6 way of importing and exporting will not help us here.
In order to export something we use the module.exports expression and we assign to it whatever we want to export. Syntax looks like following:
// Exported file (let us name it export.js)
const a = 10;
module.exports = a;
// import file (let us name it import.js)
const a = require('../path/to/yourfile/export.js');
console.log(a) // This prints 10
Require here corresponds to WHATEVER the specified file that is passed as a string argument inside the function exports. That means whatever the module.exports of that file exports.
A file can export many things, a function, a number, a boolean , an array or an object. Anything is possible, but if you want to export more than value you have to include them either in an array or an object (most commonly used method the second as we will see later).