The module object
A Node module is simply a Javascript file. Reference functions (and anything else) that might be useful to outside code to exports, as follows:
// library1.js function function1a() { return "hello from 1a"; } exports.function1a = function1a;
We now have a module that can be required by another file. Back in our main app, let's use it:
// app.js const library1 = require('./library1'); // Require it const function1a = library1.function1a; // Unpack it let s = function1a(); // Use it console.log(s);
Note how it was not necessary to use the .js
suffix. We’ll discuss how Node resolves paths shortly.
Let's make our library a little bigger, growing it to three functions, as shown:
// library1.js exports.function1a = () => "hello from 1a"; exports.function1b = () => "hello from 1b"; exports.function1c = () => "hello from 1c"; // app.js const {function1a, function1b, function1c} = require('./library1'); // Require and unpack console.log(function1a()); console.log(function1b...