Create custom Node.js modules
3 minute read
This article shows how to create and use a custom Node module
Node.js module design is based on CommonJS module specification, though sources vary on the intent and history. (Some sources vary when describing intent and history.)
To begin, move reusable functions into a separate JavaScript file (called mymodules.js
in this example):
// myModule.js
module.exports.isBlank = function( inputValue ) {
var blnResult = ( ( inputValue == undefined ) ||
( inputValue == null ) ||
( inputValue == "" ) );
return blnResult;
}
module.exports.collectFilenames = function( strTargetPath ) {
var oResults = new Object;
oResults.paths = [];
oResults.paths.push( strTargetPath );
oResults.files = [];
var fs = require( 'fs' );
for ( var xDir = 0; xDir < ( oResults.paths.length ); xDir++ ) {
var sCurrDir = oResults.paths[ xDir ];
var aThisDir = fs.readdirSync( sCurrDir );
for ( var xThisFile = 0; xThisFile < ( aThisDir.length ); xThisFile++ ) {
var strFullFilename = sCurrDir + "/" + aThisDir[ xThisFile ];
var xTFStat = fs.statSync( strFullFilename );
if ( xTFStat.isFile() ) {
oResults.files.push( strFullFilename );
} else { if ( xTFStat.isDirectory() ) {
oResults.paths.push( strFullFilename );
} else {
console.log( "Skipping ", strFullFilename,
"; not a file or directory." );
} }
}
}
return oResults.files;
}
The collectFilenames function shown here is slightly different from the one introduced in Collect filenames. Here, it returns an array of strings an object.
Limiting the return type to a simple data type gives the module more flexibility, especially with older clients. Subtle errors are easier and calling code tends to be more concise and clearer.
Function declaration changes
Function declarations have changed as well because Node modules require you to assign functions to the modules.exports
object. Thus, your calling code needs to change as well:
module.exports.isBlank = function( inputValue ) { ... }
module.exports.collectFilenames = function( strTargetPath ) { ... }
As of Node v0.1.16, the module reference is optional for exports defined in the same file.
Custom module use
Once the module is created, you calling code looks something like this:
var nbt = require( "./myModule");
var fs = require( "fs" );
var strFilePath = process.argv[ 2 ];
if ( nbt.isBlank( strFilePath ) ) {
console.log( "Declaration error: Cleanup directory not specified." );
return;
}
var p = require( "path" );
var strFilePath = p.resolve( strFilePath );
var aFilenames = [];
aFilenames = nbt.collectFilenames( strFilePath );
console.log( JSON.stringify( aFilenames, undefined, 3 ) );
What remains is generally focused on the specific task.
Note: If you receive an "Error: Cannot find module 'example'
error when you require
your module, try adding a directory reference:
var nbt = require( "./myModule");
Here, we assume that myModule
is located in the same directory as the calling script.
Adjust as needed to reflect your application structure.
More info
- Node’s full module documentation
- CommonJS module specification
- npm’s Creating Node.js Modules tutorial.
- Node.js, Require, and Exports, by Karl Seguin.
- How to Node: Creating Custom Modules, by Tim Craswell (archived).
Vital statistics
- 15 Feb 2024: Migrated to new site and style
- Lasted tested February 2017:
- Node: v7.4.0
- 12 Feb 2017: First post