简体   繁体   English

在像electronicjs这样的自定义节点模块中添加命令行行为

[英]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. 我正在创建一个JavaScript库,并希望在与-g标志一起安装时用作命令。 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 node_modules / nexam / index.js

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

node_modules/nexam/lib/nexam.js node_modules / nexam / lib / nexam.js

'use strict'

exports = module.exports;

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

main.js 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添加到您的package.json文件
 "bin": { "nexam": "./index.js" } 
  1. Use commander npm package to read cli commands. 使用commander npm软件包读取cli命令。 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. 祝一切顺利。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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