On the subject of JavaScript itself we discussed modules as a means
of storing generalized code as modules thereby making this
code available for import wherever needed. In node the
import construct is called require, and the
usage is slightly different.
We saw the file messages.js earlier. Let us change
that into a module. The module version looks as follows:
messagesm.js
"use strict";
// no const, var or let before exports.
// exports is an already defined object
exports.messages = [
"A program or two a day makes the doc go away.",
"You can do it!",
"Yes you can!"
];
Usage
messagesm.js in printMessages.js
"use strict";
const msgMod = require("./messagesm"); // look mum, no .js
msgMod.messages.forEach(function (msg) {
console.log(msg);
});Executed by
$ node printMessages A program or two a day makes the doc go away. You can do it! Yes you can!
“Modules are individual JavaScript files containing code that pertains to a single concept, functionality, or library.”[8] We create them in order to use them in more than one context. As such they are a manifestation of DRY.
The following contains some variations in writing modules and the use of them. The choice is yours. You're the programmer.
messagesm1.js
"use strict";
exports.circArea = function (r) {
return Math.PI * r * r;
}
exports.circCircumference = function (r) {
return 2 * Math.PI * r;
}
Usage
"use strict";
const mod = require("./messagesm1"); // look mum, no .js
console.log(mod.circArea(4));
console.log(mod.circCircumference(4));
messagesm2.js
"use strict";
const circArea = function (r) {
return Math.PI * r * r;
}
const circCircumference = function (r) {
return 2 * Math.PI * r;
}
exports.circArea = circArea;
exports.circCircumference = circCircumference;
Usage
"use strict";
const mod = require("./messagesm2"); // look mum, no .js
console.log(mod.circArea(4));
console.log(mod.circCircumference(4));
messagesm3.js
"use strict";
let MyMath = {
circArea: function (r) {
return Math.PI * r * r;
},
circCircumference: function (r) {
return 2 * Math.PI * r;
}
}
exports.MyMath = MyMath;
Usage
"use strict";
const mod = require("./messagesm3"); // look mum, no .js
console.log(mod.MyMath.circArea(4));
console.log(mod.MyMath.circCircumference(4));
messagesm4.js
"use strict";
module.exports = {
circArea: function (r) {
return Math.PI * r * r;
},
circCircumference: function (r) {
return 2 * Math.PI * r;
}
}
Usage
"use strict";
const MyMath = require("./messagesm4"); // look mum, no .js
console.log(MyMath.circArea(4));
console.log(MyMath.circCircumference(4));
The difference is really only aesthetic. The result in all four cases:
node mathMod1 50.26548245743669 25.132741228718345