Creating and Publishing Node.js Modules

You can split off reusable JavaScript into its own libraries called modules. A Node module is simply a JavaScript file. The export or module.exports statement is used when creating a Node module. You can convert functions, objects, or primitive values into module that might be useful to outside code to exports.

Let’s say you have a function that takes two or more arrays or strings, merge them and return a new array:

Next, we’ll import the module. Destructuring assignment (curly braces around the variables) is a great way to assign many functions exported by a required module to their local variables in a single line.

Both methods given above will do the same thing. The exports is just a reference to module.exports. Node’s core modules are defined using the module.exports statement. So, to be safe, just use the module.exports.

Exporting our FileWalker class as a module

We’ll just add the module.exports = before the class keyword, as shown: