Steve Bennett
Steve Bennett

Reputation: 126295

How to write a NodeJS module that is usable from command-line and as a module?

I have a module that expects to be called from the command line, so it processes command-line arguments using yargs, and fails with a help message if it isn't provided any.

But I'd also like this module to be called from other NodeJS modules (using gulp). If I simply require(./mymodule), it will attempt to parse command line arguments and fail.

One obvious solution is to put the command-line bit in a separate module which wrappers the main module. Are there others? Is there a common pattern?

EDIT

And is there a naming convention to distinguish the wrapper from the main module?

Upvotes: 0

Views: 65

Answers (1)

eblahm
eblahm

Reputation: 2644

I would probably just use a wrapper script for the command line invocation, as you alluded to. I feel like thats the more common pattern in nodeland. But if I HAD to solve this problem I'd probably do something like this.

var path = require('path');
var fileBase = path.parse(__filename).base;

var lib = {
    run: function() {
        console.log('my lib is running');
    }
};

module.exports = lib;


// assuming your file is not named node.js or gulp.js
// this will execute the module only when its invoked directly via the command line 
// eg node ./path/to/mylib
process.argv.reduce(function(opts, arg) {
    if (opts || arg[0] === '-') return true;
    if (path.parse(arg).base === fileBase) {
        lib.run();
    }
}, false);

Upvotes: 2

Related Questions