Skip to main content

CommonJS Modules

Declaring a module

Use @module at the top of the file:

/**
* String utility functions.
* @module string-utils
*/
'use strict';

Exporting an object

Assign an object to module.exports and document each member:

/**
* @module math
*/

/**
* Add two numbers.
* @param {number} a
* @param {number} b
* @returns {number}
*/
exports.add = function (a, b) { return a + b; };

/**
* Subtract b from a.
* @param {number} a
* @param {number} b
* @returns {number}
*/
exports.subtract = function (a, b) { return a - b; };

Exporting a constructor

/**
* @module EventEmitter
*/

/**
* A simple event emitter.
* @class
*/
function EventEmitter() {
this._handlers = {};
}

EventEmitter.prototype.on = function (event, fn) {
(this._handlers[event] = this._handlers[event] || []).push(fn);
};

EventEmitter.prototype.emit = function (event, ...args) {
(this._handlers[event] || []).forEach(fn => fn(...args));
};

module.exports = EventEmitter;

Exporting a function as the module

Use @exports to tell JSDoc that the function is the module's main export:

/**
* Parse a CSV string into an array of row objects.
* @exports parseCSV
* @param {string} csv
* @returns {Object[]}
*/
module.exports = function parseCSV(csv) {};

See also