本文共 2805 字,大约阅读时间需要 9 分钟。
LiveQing 高性能流媒体服务器以打成压缩包的形式提供给客户使用, 同时支持 Linux 和 Windows 平台. Linux 平台打成 tar 包, Windows 平台打成 zip 包. 通过 NodeJS 运行打包脚本, 实现了打包过程的自动化.
用到一个打包的核心库 , 这个 archiver 库, 支持 glob 表达式, 可以非常方便的指定 需要打包哪些文件和目录 和 排除哪些文件和目录. 关于 arhiver 对 glob 的支持, 可以查看. archiver 功能强大到可以指定工作目录 cwd
, 给压缩包指定前缀目录 prefix
.
一个将字节大小格式化成 human-readable 的库. 方便在压缩过程中显示进度信息.
结合 tj 创作的这个命令行工具, 快速生成一个打包的命令, 并将打包的格式做成命令行选项.
以下是执行 node release.js -h
输出
Usage: release [options] [command] Options: -V, --version output the version number -F, --format [tar,zip] archive format [tar] -h, --help output usage information Commands: clean
const archiver = require('archiver');const prettyBytes = require('pretty-bytes');const os = require('os');const path = require('path');const fs = require('fs');const program = require('commander');var dir = path.basename(__dirname);function doArchive() { switch (program.format) { case 'zip': var output = fs.createWriteStream(`${__dirname}/${dir}.zip`); var archive = archiver('tar', { zlib: { level: 9 } }) break; case 'tar': var output = fs.createWriteStream(`${__dirname}/${dir}.tar.gz`); var archive = archiver('tar', { gzip: true }); break; default: console.log('unknow format'); program.help(); break; } output.on('close', function () { console.log(os.EOL + prettyBytes(archive.pointer()) + ' total bytes'); }); archive.on('warning', function (err) { if (err.code === 'ENOENT') { console.log(err); } else { throw err; } }).on('error', function (err) { throw err; }).on('progress', data => { process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(`${prettyBytes(data.fs.processedBytes)} / ${prettyBytes(data.fs.totalBytes)}`); }) archive.pipe(output); archive.glob(`**`, { cwd: path.resolve(__dirname, "dist"), dot: true, ignore: ['logs/**/*', 'temp/**/*'] },{ prefix: dir }) console.log(`do ${program.format} ...`); archive.finalize();}program.version(require('./package.json').version) .option('-F, --format [tar,zip]', 'archive format [tar]', 'tar')program.command('clean').action(function () { if(fs.existsSync(path.resolve(__dirname, `${dir}.zip`))){ fs.unlinkSync(path.resolve(__dirname, `${dir}.zip`)); } if(fs.existsSync(path.resolve(__dirname, `${dir}.tar.gz`))){ fs.unlinkSync(path.resolve(__dirname, `${dir}.tar.gz`)); } console.log('clean done.'); process.exit();})program.command('*', '', { noHelp: true}).action(function () { program.help();})program.parse(process.argv);doArchive();
转载地址:http://ogvvi.baihongyu.com/