Home  >  Article  >  Web Front-end  >  Building command line tools using node.js

Building command line tools using node.js

不言
不言Original
2018-04-10 17:04:451444browse

The content of this article is to use node.js to build command line tools. It has certain reference value. Friends in need can refer to it


Tool Description

  • inquirer.js: A node.js module that encapsulates common command line interactions. This module can easily build a new command line application.

  • shell.js: Cross-platform unix shell command module.

  • Node version: Since the asynchronous method of inquirer.js returns Promise by default, it is recommended to use node.js>=8.

Goal

There are a large number of projects at work that need to be tested, compiled, updated version number, submitted, and even the commands executed are the same in the last step before going online. Here We use command line tools to automate these steps with one click and perform pre-checks to prevent errors and omissions.

Preparation

  1. Create a new Node.js project.

  2. Create the file bin/my-cli.js. The node.js project usually places the cli entry in the bin directory and other modules in the lib directory.

  3. Add #!/usr/bin/env node to the header of the bin/my-cli.js file.

  4. Add "bin": {"my-cli": "./bin/my-cli.js"}, to package.json, declare us The command to use.

  5. Execute npm link in the project root directory to create a global command my-cli.

Slightly modify my-cli.js, add the code console.log("I am a cli tool!"), and then Open the console and run the my-cli command. If you see the console output I am a cli tool!, it means success.

Installation dependencies

First install the two main dependent modules (please refer to the official documentation for the use of these two modules)

npm install inquirer shelljs

Build release process automation

The next step is to implement the automation of testing, updating version numbers, building, and automatically submitting releases

const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

const { version } = await inquirer.prompt([
  {
    type: 'list',
    name: 'version',
    message: '版本号更新方式:',
    choices: [
      {
        name: `v${semver.inc(pkg.version, 'patch')}: Fix Bugs / Patch`,
        value: 'patch'
      },
      {
        name: `v${semver.inc(pkg.version, 'minor')}: Release New Version`,
        value: 'minor'
      },
    ]
  }
]);
// 拉取最新版本
shelljs.exec('git pull');
// 运行测试
shelljs.exec('npm test');
//通过npm version更新版本号,但不自动添加git tag,而是在构建完成后由cli工具添加
shelljs.exec(`npm version ${version} --no-git-tag-version`);
// 构建
shelljs.exec('npm run build');
// 提交发布代码
const nextVersion = semver.inc(pkg.version, version);
shelljs.exec('git add . -A');
shelljs.exec(`git commit -m "build: v${nextVersion}"`)
shelljs.exec(`git tag -a v${nextVersion} -m "build: ${nextVersion}"`);
shelljs.exec("git push")
shelljs.exec("git push --tags");

Add new features: configuration check

Next add a function to my-cli:

When checking the check-baidu- of the my-cli object in package.json When the id attribute is true, check whether the config.json of the project exists baidu-idattribute

if (pkg['my-cli'] && pkg['my-cli']['check-baidu-id']) {
  const configPath = path.join(process.cwd(), 'config.json');
  if (!fs.existsSync(configPath)) {
    shelljs.echo('找不到config.json');
    shelljs.exit(1);
  }
  const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  if (!config['baidu-id']) {
    shelljs.echo('config.json缺少属性[baidu-id]');
    shelljs.exit(1);
  }

Last step

Such a simple cli program has been implemented. It automates the build and release process, and also performs configuration checks before building and releasing.

In actual projects, in order to improve the stability of the program, it is also necessary to add functions such as checking whether package.json exists in the current project, preventing json parsing errors, and confirming before execution. For details, see the sample code.

Example code

Address: https://github.com/Aturan/node-cli-example

Conclusion

Although the above functions use shell It can be implemented, but writing code is not so convenient and fast, and once more complex problems are encountered, it will be very troublesome to implement them using the shell, and maintenance is also a problem.

PS. In fact, you can also use python. For Ubuntu, it is an advantage that the system comes with Python. It can be used directly on the server without installing an environment. In addition, Python also has an Inquirer module.

Related recommendations:

Example details how node.js obtains SQL Server database

Node.js module system

The above is the detailed content of Building command line tools using node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn