簡體   English   中英

在像electronicjs這樣的自定義節點模塊中添加命令行行為

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

我正在創建一個JavaScript庫,並希望在與-g標志一起安裝時用作命令。 問題是我該如何實施這種行為。 我應該能夠將其用作命令。

由於電子的行為方式如此,我以為我可以參考電子代碼,但沒有從發生的地方獲得電子代碼。


我已經實現了以下行為

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();

輸出:

$ node main.js
Hello World

我想這樣使用

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

$ nexam --sayHello
Hello World

這里有兩件事要處理。

  1. bin添加到您的package.json文件
 "bin": { "nexam": "./index.js" } 
  1. 使用commander npm軟件包讀取cli命令。 它非常易於使用。 這是他們文檔頁面中的摘錄。
 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); 

祝一切順利。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM