Defining a module
Modules are the basic building blocks for constructing Node.js applications. A Node.js module encapsulates functions, hiding details inside a well-protected container, and exposing an explicitly-declared list of functions.
There are two module formats that we must consider:
- The traditional Node.js format based on the CommonJS standard has been used since Node.js was created.
- With ES2015/2016 a new format, ES6 Modules, has been defined with a newÂ
import
keyword. ES6 modules will be (or is) supported in all JavaScript implementations.
Because ES6 modules are now the standard module format, the Node.js Technical Steering Committee (TSC) is committed to first-class support for ES6 modules.
We have already seen modules in action in the previous chapter. Every JavaScript file we use in Node.js is itself a module. It's time to see what they are and how they work. We'll start with CommonJS modules and then quickly bring in ES6 modules.
In the ls.js
example in Chapter 2, Setting up Node...