node tar

262 阅读1分钟
#!/usr/bin/env node

import path from 'path';
import tar from 'tar';
import fs from 'fs';

const cwd = process.cwd();  // 获取当前工作目录完整路径
const cwdName = path.basename(cwd); // 获取当前目录名
const bundleFileNames = [`${cwdName}.tar.gz`, `${cwdName}.tgz`]; // 打包文件以当前目录名命名
const bundleFileName = bundleFileNames[0];

const bundleFileList = getFileAndFolderList(cwd);
await bundleFiles(bundleFileName, bundleFileList, cwdName);
moveFileToPrevDir(bundleFileName);
console.log(`生成成功, 文件保存为在上级目录的 ${bundleFileName}`);

/**
 * 打包文件
 * @param string bundleFileName 打包生成的文件名
 * @param string[] bundleFileList 被打包的文件列表
 * @param string prefix 将被打包的文件在tar包中赋予一个上级目录
 * @returns 
 */
async function bundleFiles(bundleFileName, bundleFileList, prefix) {
  const options = {
    gzip: true,
    file: bundleFileName,
    sync: true,
  }
  if (prefix) options.prefix = prefix;

  return await tar.create(options, bundleFileList);
}

/**
 * 获取将被打包的文件列表
 * @param string dir 文件夹
 * @returns 
 */
function getFileAndFolderList(dir, options = {}) {
  let list = fs.readdirSync(dir);
  list = list.filter(item => {
    if (bundleFileNames.includes(item)) return false;
    if (options.excludeGit && item === '.git') {
      return false;
    }
    return true;
  })
  return list;
}

/**
 * 将打包成功的gzip包移动到上层文件夹
 * @param string fileName 
 * @returns 
 */
function moveFileToPrevDir(fileName) {
  fs.renameSync(fileName, `../${fileName}`);
}