node中exec函数的使用

4,454 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情

接上篇:初步探索commander的使用 - 掘金 (juejin.cn)

思路

今天开发的功能是执行命令,可以快捷的对文件夹压缩

  1. 通过百度发现nodejs是可以执行命令的。child_processexec函数。所以打算直接使用shell命令搞。

exec

详情: nodejs.cn/api/child_p…

child_process.exec(command[, options][, callback])

command

string类型, 要运行的命令。

options 可选参数

参数解释
cwd子进程的当前工作目录。 默认值: process.cwd()
env环境变量键值对
encodingutf8
shell用于执行命令的shell
......

callback

回调函数

  1. 使用tar命令进行打包。www.runoob.com/linux/linux…

实现

  • 首先简单的封装一下exec函数, 后续的一些功能也许会用到, 创建exec.ts。封装如下

import { exec } from "child_process";

/**
 * 执行shell命令
 * 
 * @param 命令
 * @returns 
 */
export function useExec(shell: string) {
  return new Promise((res, rej) => {
    exec(shell, (err, stdout, stderr) => {
      if (err) rej(err);
      res({
        stdout,
        stderr,
      });
    });
  });
}
  • 创建tar.ts文件,封装函数和命令, 对文件打包
/*
 * @Author: Aisanyi
 * @Date: 2022-04-03 20:09:17
 * @LastEditors: Aisanyi
 * @LastEditTime: 2022-04-04 13:33:23
 * @Description: 执行命令
 */

import chalk from "chalk"
import { useExec } from "./exec.js"

/**
 * 
 * @param outDir 打包之后的路径以及名称
 * @param rootDir 需要打包的路径和名称
 */
export function tarFolder(outDir: string, rootDir: string) {
  console.log(chalk.gray('打包开始'))
  useExec(`tar -zcPf ${outDir}.tar.gz ${rootDir}`).then(res => {
    console.log(chalk.gray('打包结束'))
  })
}
  • index.ts 添加tar命令。可选参数 fileurl , 默认当前路径下的bin文件夹。
program
  .command("tar [fileurl]")
  .description("打包")
  .action((fileurl: string = 'bin') => {
    tarFolder(fileurl, fileurl);
  });

测试

运行 pnpm testdeploy-cli tar,结果如下: image.png image.png

功能基本实现, 后续修改会在以后的文章完整记录。