Node Modules
Introduction
The use of modules in Node is central to its popularity as a development platform as it allows software building blocks to be wired together quickly and easily. But as with most things in the Node world, there are several different ways that modules can be created and then used…
The Basics
Including a module is simple enough — for a module installed via npm, you do this:
var moduleReference = require( 'module-name' ) ;and for a module that is part of your application, you do this:
var moduleReference = require( 'path-to-module/module-name' ) ;But what does this actually do? Answer — in effect, the following code is executed automatically inside the module file:
var exports = module.exports = {} ;Initially, both exports and module.exports point to the same empty object:
So module.exports gets wired up via the require() function, and exports is an additional reference to this inside the module file. You need to be a bit careful how you use these two possible ways of addressing the “output” of the module file. Initially both names are references to the same object, and assigning properties (e.g. exports.forename = “Doctor” and module.exports.surname = “Who”) will make changes to the same referenced object. However if you assign a value directly to exports (e.g. exports = function( …. )) then you will end up with this:
So the module will export nothing (module.exports is what finally gets exported from the module, exports is just a shortcut).
So here are the two alternatives for a module that exports two functions:
Option 1
module.exports = {
function doSomething( <parameters> ) {
return <something> ;
},
function doSomethingElse( <parameters> ) {
return <something-else> ;
}
}Option 2
exports.doSomething = function( <parameters> ) {
return <something> ;
} ;
exports.doSomethingElse = function( <parameters> ) {
return <something-else> ;
} ;Both do exactly the same thing, the first option is possibly better / more concise for a simple module, the latter is probably the best choice for a module with more and / or longer exported methods. Choose whichever you prefer, just don’t mix the two as this will undoubtedly lead to confusion, unexpected errors and possibly insanity…
Option 3
You could also use a local variable to “collect up” the methods and properties to want to export, which can make your code a bit more readable by separating out function definitions (we’re also taking advantage of “function hoisting”, where we can refer to functions before they have been defined — this is nice because the top part of the script file clearly describes the methods the module exports, leaving the code that implements those methods out of the way):
var myModule = exports ;myModule.doSomething = doSomething ;
myModule.doSomethingElse = doSomethingElse ;function doSomething( <parameters> ) {
return <something> ;
} ;
function doSomethingElse( <parameters> ) {
return <something-else> ;
} ;
Export an Object
This common pattern is used to create a module which exports a number of methods or functions, and possibly some properties (although exposing properties may not be advisable if you don’t have a clear understanding of places in your code where these properties may be used and/or changed). Typically this pattern will be used for creating “utility” libraries that expose a number of useful functions.
Example
Calling Code
var colours = require( './colours' ) ;console.log( 'Hex code #FF0000 is ' + colours.getName( 'FF0000' ) ;
Module (colours.js)
var colours = module.exports ;// Public method available to calling code
colours.getname = function( hexcode ) {
hexcode = parse( hexcode ) ;
switch( hexcode ) {
case 'FF0000':
return 'Red' ;
break ;
case '00FF00':
return 'Green' ;
break ;
case '0000FF':
return 'Blue' ;
break ;
default:
return 'Sorry, I haven\'t got a clue!' ;
}// Private function only available internally to this module
function parse( hexcode ) {
if ( typeof hexcode !== 'string' ) return '' ;
if ( hexcode.length < 6 || hexcode.length > 7 ) return '' ;
if ( hexcode.length == 7 ) hexcode = hexcode.substr( 1 ) ;
return hexcode ;
}
Export a Function
Another common pattern involves exporting a function which creates an object when called, i.e. a factory function. This allows you to pass in options that can be used to configure the created object.
Example 1
Calling Code (server.js)
var Meerkat = require( './meerkat' ) ;
var aleksandr = new Meerkat( { name: 'Alexsandr' } ) ;
console.log( 'My name is ' + aleksandr.name + ' and I am a ' + aleksandr.species ) ;
var vassily = new Meerkat( { name: 'Vassily' } ) ;
console.log( 'My name is ' + vassily.name + ' and I am a ' + vassily.species ) ;Module Code (meerkat.js)
var Meerkat = function( options ) {
return( { name: options.name, species: 'meerkat' } ) ;
} ;module.exports = Meerkat ;
Output
My name is Alexsandr and I am a meerkatMy name is Vassily and I am a meerkat
Example 2
Express middleware is created using this pattern. For example, a simple module to log details of all requests could be written as follows:
Get Andy Neale’s stories in your inbox
Join Medium for free to get updates from this writer.
Calling Code (server.js)
var express = require( 'express' ) ;
var logger = require( './logger.js' ) ;
var app = express() ;app.use( logger( { prefix: 'server.js' } ) ) ;app.get( '*', function( req, res, next ) {
res.send( 'Thank you for visiting' ) ;
} ) ;
app.listen( 3000 ) ;
console.log( 'Listening on port 3000...' ) ;
Module (logger.js)
var moment = require( 'moment' ) ;module.exports = factory ;function factory( options ) {
return function logger( req, res, next ) {
console.log( options.prefix + ': '
+ req.method + ' ' + req.path + ' '
+ moment().format( 'DD-MM-YYYY HH:mm:ss' ) ) ;
next() ;
}
}
(Note that the returned function is given a name (“logger”), even though it could have been left as an anonymous function, so that the name shows up in stack traces. If an error occurred in the logger module, it would show up as e.g.
TypeError: moment(...).formt is not a function
at logger (W:\SANDBOX\node-modules\logger.js:8:85)
at Layer.handle [as handle_request] (W:\SANDBOX\node-modules\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (W:\SANDBOX\node-modules\node_modules\express\lib\router\index.js:312:13)
...If this was a big module, having the name of the function in which the error occurred might be more helpful than just showing the line/column numbers.)
Usage
The logger module works by creating a function that adheres to the expected signature of an Express middleware i.e. a function that received req, res and next parameters.
Launching the server (“node server.js”) and browsing to the following URLs:
http://localhost:3000/lost
http://localhost:3000/stuffed
http://localhost:3000/shorty
will result the following console output:
server.js: GET /lost 14–08–2015 15:11:24server.js: GET /stuffed 14–08–2015 15:11:30server.js: GET /shorty 14–08–2015 15:11:32
Further Reading
http://www.sitepoint.com/understanding-module-exports-exports-node-js/
https://darrenderidder.github.io/talks/ModulePatterns/#/
https://nodejs.org/api/modules.html






