一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情 。
思路
今天开发的功能是执行命令,可以快捷的对文件夹压缩
- 通过百度发现
nodejs是可以执行命令的。child_process的exec函数。所以打算直接使用shell命令搞。
exec
child_process.exec(command[, options][, callback])
command
string类型, 要运行的命令。
options 可选参数
| 参数 | 解释 |
|---|---|
| cwd | 子进程的当前工作目录。 默认值: process.cwd()。 |
| env | 环境变量键值对 |
| encoding | utf8 |
| shell | 用于执行命令的shell |
| ... | ... |
callback
回调函数
- 使用
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 test,deploy-cli tar,结果如下:
功能基本实现, 后续修改会在以后的文章完整记录。