CLI, as an abbreviation of Command-line Interface, can receive user's input and give an immediate response in terminal.

In Node.js, globally installed packages have this kind of command line interface, taking 'http-server' as a brief example here:

What if we wanna make one like that? Easy, create files below first:

After that, we will create a my-cli.js file in 'bin' folder:

#!/usr/bin/env node

console.log('hello my-cli');

Note that: The first line indicates it's an executable file in Node.js environment, and that's indispensable。

Also package.json config is a necessary step:

{
"author": "Scott",
"license": "MIT",
"name": "my-cli",
"version": "1.0.0",
"description": "my-cli",
"bin": {
"my-cli": "bin/my-cli.js"
},
"preferGlobal": "true"
}

As above, we provide a 'bin' configuration which has global command 'my-cli' pointing to 'bin/my-cli.js', and the last property 'preferGlobal' states clearly it supports global installation.

Now we open a terminal and run the following command in 'my-cli' dev folder:

As picture shows, we can run 'my-cli' command globally after installing our package via 'npm install -g .', magic happens!

Now we already complete a simple CLI program, but is it short of something? Em..., maybe we can add interactions for command line, and also, make it support two usage: global execution and normal import.

After a slight improvement on file structure:

As we see, a 'lib' folder was created for some logic files, a demo code shows below:

let chalk = require('chalk');

let sayHello = name => {
// special fonts by 'chalk' lib
return chalk.bold('Hello, ') + chalk.bold.bgRed(name);
}; exports.sayHello = sayHello;

We defined a 'sayHello' function and return a greeting word by passing the name, we also use the 'chalk' lib for special fonts in terminal.

Now let's have a glance at 'bin/my-cli.js':

#!/usr/bin/env node

let readline = require('readline');
let lib = require('../lib/index.js'); // interaction
let interface = readline.createInterface({
input: process.stdin,
output: process.stdout
}); // question and answer
interface.question('What is your name? ', answer => {
let greeting = lib.sayHello(answer); console.log(greeting); interface.close();
});

'readline' module is an encapsulation on stdin and stdout, used to prompt and receive user's input.

And last, some modifications should be done in package.json:

{
"author": "Scott",
"license": "MIT",
"name": "my-cli",
"version": "1.0.0",
"description": "my-cli",
"bin": {
"my-cli": "bin/my-cli.js"
},
"main": "lib/index.js",
"preferGlobal": "true",
"dependencies": {
"chalk": "^1.1.3"
}
}

In addition to add 'bin' config, we also have the 'main' property, it's for the import in other lib, we will introduce it later.

Now we run 'npm install -g .' again to install globally, and open a new terminal:

As the image shows, our program received command arguments and printed the right result.

We mentioned above, our program can be a common package imported in other libs, now we create a test folder to show the demo:

This directory is simple, only includes a test.js and node_modules folder, and in node_modules it consists of my-cli folder:

Now we just take a look at the test.js:

let cli = require('my-cli');

let greeting = cli.sayHello('Jack');

console.log(greeting);

And then we run this file in terminal, and result as below:

At last, we can publish this package to npm repository, for this step, you may refer to the official docs.

Reference:

https://bretkikehara.wordpress.com/2013/05/02/nodejs-creating-your-first-global-module

https://nodejs.org/api/readline.html

Node: 开发命令行程序英文版 (Create Your Own CLI)的更多相关文章

  1. Node: 开发命令行程序

    CLI 的全称是 Command-line Interface (命令行界面),即在命令行接受用户的键盘输入并作出响应和执行的程序. 在 Node.js 中,全局安装的包一般都具有命令行界面的功能,例 ...

  2. Node.js 命令行程序开发教程

    nodejs开发命令行程序非常方便,具体操作方式查看下面几篇文章 http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html ...

  3. Node.js 命令行程序开发资料

    Node.js 命令行程序开发教程http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html用Node.js创建命令行工具ht ...

  4. Node.js 命令行程序开发教程 ---------http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html

    五.yargs 模块 shelljs 只解决了如何调用 shell 命令,而 yargs 模块能够解决如何处理命令行参数.它也需要安装. $ npm install --save yargs yarg ...

  5. 2019-11-29-dotnet-使用-System.CommandLine-写命令行程序

    title author date CreateTime categories dotnet 使用 System.CommandLine 写命令行程序 lindexi 2019-11-29 08:33 ...

  6. 2019-8-31-dotnet-使用-System.CommandLine-写命令行程序

    title author date CreateTime categories dotnet 使用 System.CommandLine 写命令行程序 lindexi 2019-08-31 16:55 ...

  7. dotnet 使用 System.CommandLine 写命令行程序

    在写命令行程序的时候,会遇到命令行解析的问题,以及参数的使用和规范化等坑.现在社区开源了命令行项目,可以帮助小伙伴快速开发命令行程序,支持自动的命令行解析和规范的参数 我写过一篇关于命令行解析的博客C ...

  8. 如何用node编写命令行工具,附上一个ginit示例,并推荐好用的命令行工具

    原文 手把手教你写一个 Node.js CLI 强大的 Node.js 除了能写传统的 Web 应用,其实还有更广泛的用途.微服务.REST API.各种工具……甚至还能开发物联网和桌面应用.Java ...

  9. 如何用Node编写命令行工具

    0. 命令行工具 当全局安装模块之后,我们可以在控制台下执行指定的命令来运行操作,如果npm一样.我把这样的模块称之为命令行工具模块(如理解有偏颇,欢迎指正) 1.用Node编写命令行工具 在Node ...

随机推荐

  1. MySQL悲观

    //0.开始事务 begin;/begin work;/start transaction; (三者选一就可以) //1.查询出商品信息 for update; //2.根据商品信息生成订单 inse ...

  2. EasyDSS高性能RTMP、HLS(m3u8)、HTTP-FLV、RTSP流媒体服务器和EasyDSS云平台异同

    背景分析 不同于EasyDSS流媒体服务器与EasyDSS流媒体解决方案(EasyDSS流媒体解决方案就是通过EasyDSS流媒体服务器完善业务层研发而来),EasyDSS流媒体服务器和EasyDSS ...

  3. php代码规范->如何写出规范且易于理解的项目代码-ZX版

    2019年5月17日10:50:12 前序: 目前是想到哪写到哪,后面有时间在整理成具体文章 很多时候,PHP代码风格过于自由,导致一个项目有N多种写法风格,有些人为了自己认为的技术"高&q ...

  4. haproxy转发真实IP给web

    1.在haproxy.cfg中加入下面参数. option forwardfor               #如果后端服务器需要获得客户端真实ip需要配置的参数,必须要放在listen模块下 2.如 ...

  5. nginx yaf需要注意的问题

    nginx yaf需要注意的问题 显示视图的方法<pre> $this->getView()->assign(array('pack'=>$return['pack'], ...

  6. jdk7中hashmap实现原理和jdk8中hashmap的改进方法总结

    1. HashMap的数据结构 数据结构中有数组和链表来实现对数据的存储,但这两者基本上是两个极端. 数组 数组存储区间是连续的,占用内存严重,故空间复杂的很大.但数组的二分查找时间复杂度小,为O(1 ...

  7. Oracle RAC 创建实例出错(非+DATA目录)的简单处理

    今天进行oracle的rac测试 发现开发同事没有写好 oracle rac的设置.  创建完之后就会报错了 因为自己对oracle 的RAC 不太熟悉 不太会用.. 所以用 一个比较简单的办法. a ...

  8. c++11多线程记录4:死锁

    简单示例 举个例子,桌上有一支笔和一张纸,小A和小B都要拿到纸笔写字 小A拿了笔,小B拿了纸,这时就形成了死锁(两人都不愿意让出纸笔). 其实只要稍加控制就可以避免这种情况:规定必须先拿到纸再能去尝试 ...

  9. 最少硬币数——Java

    问题:有n种硬币,面值分别为v1,v2,v3,…,vn,存于数组T[1:n]中,可以使用的各种面值的硬币个数存于数组Coins[1:n]中.对任意钱数0≤m≤20001,设计一个用最少硬币找钱m的方法 ...

  10. UOJ399 CTSC2018 假面 期望、DP

    传送门 \(Q \leq 200000 , C \leq 1000 , m_i \leq 100\)-- 先考虑如何维护最后一次操作时所有人的血量期望.不难发现我们需要的复杂度是\(O(Qm_i)\) ...