- Building Enterprise JavaScript Applications
- Daniel Li
- 231字
- 2021-07-23 16:31:08
Adoption of the CommonJS standard
In Node.js, modules are written in the CommonJS format, which provides two global objects, require and exports, that developers can use to keep their modules encapsulated. require is a function that allows the current module to import and use variables defined in other modules. exports is an object that allows a module to make certain variables publicly available to other modules that require it.
For example, we can define two functions, helloWorld and internal, in greeter.js:
// greeter.js
const helloWorld = function (name) {
process.stdout.write(`hello ${name}!\n`)
};
const internal = function (name) {
process.stdout.write('This is a private function')
};
exports.sayHello = helloWorld;
By default, these two functions can only be used within the file (within the module). But, when we assign the helloWorld function to the sayHello property of exports, it makes the helloWorld function accessible to other modules that require the greeter module.
To demonstrate this, we can require the greeter module in main.js and use its sayHello export to print a message to the console:
// main.js
const greeter = require('./greeter.js');
greeter.sayHello("Daniel");
Now, when we run main.js, we get a message printed in the Terminal:
$ node main.js
hello Daniel!