如何使用 Node.js 开发交互式命令行应用程

2025-02-06 11:59:53
推荐回答(1个)
回答1:

工作中打造一款属于自己的命令行工具,很多时候可以很大程度上减少重复工作提高开发效率,简单介绍一下开发一个命令行工具的步骤。

拿快速构建前端项目脚手架为例:

主要开发步骤:

1.创建项目

$ npm init
name: (app-cli)
version: (1.0.0)
description: A command-line tool for creating  a custom project
entry point: (index.js)
author:
license: (MIT)

会生成一个package.json文件,在该文件中添加一个bin字段,
bin字段的key就是你的命令,value指向相对于package.json的路径,
不同的key对应不同的命令。关于 bin 字段更多信息请参考 npm 文档中 package.json 一节。

{  "name": "app-cli",  "version": "1.0.0",  "description": "A command-line tool for creating  a custom project",  "bin":{    "createApp":"/bin/index.js"
},  "main": "index.js",  "author": "",  "license": "MIT"}

2.创建bin/index.js文件

#!/usr/bin/env node console.log('Hello, world!');

注意要添加shebang 来指定脚本运行环境

3.测试
开发时为了方便调试,可以全局执行命令,需要把开发模块镜像到全局,在开发目录中执行命令:

npm link

{userpath}\AppData\Roaming\npm\createapp -> {userpath}\AppData\Roaming\npm\node_modules\app-cli\bin\index.js
{userpath}\AppData\Roaming\npm\node_modules\app-cli -> {userpath}\myproject\app-cli
$ createapp
Hello, world!

这样就可以方便调试代码了。

命令行工具常用模块介绍:

  • Commander.js 命令行交互框架
    使用方法:

  • #!/usr/bin/env node/**

  • * Module dependencies.

  • */var program = require('commander');


  • program

  •  .version('0.0.1')

  •  .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');if (program.bbqSauce) console.log('  - bbq');console.log('  - %s cheese', program.cheese);

  • 2.yargs 另一个命令行交互框架

  • #!/usr/bin/env node  require('yargs')

  •    .usage('$0 [args]')

  •    .command('hello [name]', 'welcome ter yargs!', {      name: {        default: 'default name'

  •      }

  •    }, function (argv) {      console.log('hello', argv.name, 'welcome to yargs!')

  •    })

  •    .help()

  •    .argv

  • $ node example.js --help

  • output

  • test [args]


  •  Commands:

  •    hello  welcome ter yargs!


  •  Options:

  •    --name, -n  provide yer name!

  •    --help      Show help          

  • 3.Inquirer UI交互就是提示框

  • var inquirer = require('inquirer');

  • inquirer.prompt([/* Pass your questions in here */]).then(function (answers) {    // Use user feedback for... whatever!!});

  • Commander.js

  • Inquirer.js

  • chalk.js

  • 安装使用:

  • $ npm install app-cli -g

  • $ createApp