手摸手node交互式上传代码

265 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第 2 天,点击查看活动详情

前言:学习 node 的第 n 天


效果图

image.png

功能

  1. 实现交互式提交代码

前提

1.requirer 学习(node 交互式命令)
2.node 执行命令
3.编写 shell 脚本

requirer

安装

npm install requirer

文档

requirer

例子

//index.js
const inquirer = require("inquirer");
inquirer
  .prompt([
    { type: "input", name: "inputResult", default: "1", message: "请输入值" },
    { type: "number", name: "numberResult", default: 1, message: "请输入值" },//输入值需为数值否则取默认值
    { type: "confirm", name: "confirmResult", default: true, message: "请输入值" },//选择yes/no
    {type: "list",name: "listResult",default: 'npm',message: "请输入值",
     choices: [
      {name: 'npm',value: 'npm',},
      {name: 'yarn',value: 'yarn'},
     ]
    },//选择列
    {type: "rawlist",name: "rawlistResult",default: 'npm',message: "请输入值",
     choices: [
      {name: 'npm',value: 'npm',},
      {name: 'yarn',value: 'yarn'},
     ]
    },//问题选择列
    {type: "expand",name: "expandResult",default: 'n',message: "请输入值",
      choices: [
       {key:'n',name: 'npm',value: 'npm',},
       {key:'y',name: 'yarn',value: 'yarn'},
      ]
    },
    {type: "checkbox",name: "checkboxResult",default: 'n',message: "请输入值",
      choices: [
       {name: 'npm',value: 'npm',},
       {name: 'yarn',value: 'yarn'},
      ]
    },//复选
    { type: "password", name: "passwordResult", default: "1", message: "请输入值" },//密码输入
  ])
  .then((answers) => {
    // Use user feedback for... whatever!!
  })
  .catch((error) => {
    if (error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });

运行结果图

1654656960(1).jpg

execSync

  1. 执行系统的命令行
//获取运行中的端口
const childProcess = require('child_process')
const { execSync } = childProcess
let data = execSync('echo | netstat -an')
console.log(data.toString())

编写 shell 脚本

  1. 新增一个简单的index.sh文件
#! /bin/bash
echo 'hellow world'

可以简单的运行一下 bash index.sh

image.png

进入正题实现交互式上传代码

  1. 新建文件index.js
//index.js
const childProcess = require('child_process')
const { execSync } = childProcess
const inquirer = require('inquirer')
inquirer.prompt([
  {
    message: '请输入提交代码的注释',
    name: 'codeMsg'
  }
]).then((answers) => {
  execSync('bash index.sh', {
    env: Object.assign({ codeMsg: answers.codeMsg }, process.env)
  })
})
  1. 新建文件index.sh
#! /bin/bash
git pull
git add .
git commit -m $codeMsg
git push
  1. 执行node index.js

image.png