简体   繁体   中英

Adding comand-line behaviour in custom node-module like electronjs does

I am creating a JavaScript library and I want it to be used as a command when installed with -g flag. Question is how could I implement such behavior. I should be able to use that as a command.

Since electron behaves in such a way I thought I could refer electron code but didn't get from where it is happening.


I've implemented following behavior

node_modules/nexam/index.js

module.exports = require("./lib/nexam");

node_modules/nexam/lib/nexam.js

'use strict'

exports = module.exports;

exports.sayHello = function(){
   console.log("Hello World");
}

main.js

const nexam = require("nexam");

nexam.sayHello();

Output:

$ node main.js
Hello World

I want to use it like this

$ npm install -g nexam
$ nexam --version
nexam v1.0.0

$ nexam --sayHello
Hello World

There are two things to handle here.

  1. Add bin to you package.json file
 "bin": { "nexam": "./index.js" } 
  1. Use commander npm package to read cli commands. Its very easy to use. Here is a snippet from their documentation page.
 var program = require('commander'); program .version('0.1.0') .option('-p, --peppers', 'Add peppers') .option('-P, --pineapple', 'Add pineapple') .option('-b, --bbq-sauce', 'Add bbq sauce') .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') .parse(process.argv); console.log('you ordered a pizza with:'); if (program.peppers) console.log(' - peppers'); if (program.pineapple) console.log(' - pineapple'); console.log(' - %s cheese', program.cheese); 

All the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM