javascript - 像 Electronjs 一样在自定义 Node 模块中添加命令行行为

标签 javascript node.js node-modules

我正在创建一个 JavaScript 库,并且希望在使用 -g 标志安装时将其用作命令。问题是我怎样才能实现这种行为。我应该能够将其用作命令。

由于电子的行为方式如此,我想我可以引用 electron代码,但没有从发生的地方获取。

<小时/>

我已经实现了以下行为

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"
      }
  • 使用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);
    

    祝一切顺利。

    关于javascript - 像 Electronjs 一样在自定义 Node 模块中添加命令行行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458384/

    相关文章:

    javascript - 如何使用 mongojs 遍历整个 MongoDB 集合?

    javascript - Append() 方法没有复制样式

    javascript - 显示登录或输入相关内容的图层的最佳方式? [facebook 弹出样式]

    node.js - Browserify 文档未定义

    node.js - package.json 中的 npm 语义版本控制 - 它仅适用于 1.0.0 及更高版本吗?

    node.js - 如何使用 Node 模块 kappa?

    javascript - 获取网页标题和段落

    node.js - 如何在Cloud9IDE中使用非纯JS(C++)Node.js模块?

    node.js - yarn pnp 回退到默认要求

    node.js - 从 Gitlab 私有(private)存储库导入 Node 模块时出错