Last active
November 13, 2018 08:00
-
-
Save Dafrok/c37ff4ebc3eca2393228b7bd8e665593 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file 在内存中打包 zip 文件的类,需要设置 `/var/run/${namespace}` 的权限为777 | |
* @author [email protected] | |
*/ | |
import * as fs from 'fs'; | |
import * as path from 'path'; | |
import * as mkdirp from 'mkdirp'; | |
import * as archiver from 'archiver'; | |
import * as copydir from 'copy-dir'; | |
import * as rmdir from 'rimraf'; | |
export default class Pack { | |
constructor(dir, namespace = 'pack') { | |
this.runtimeDir = `/var/run/${namespace}`; | |
this.baseDir = path.join(this.runtimeDir, dir); | |
this.sourceDir = path.join(this.baseDir, './source'); | |
this.outputDir = path.join(this.baseDir, './output'); | |
mkdirp.sync(this.sourceDir); | |
mkdirp.sync(this.outputDir); | |
} | |
// 从文件夹导入 | |
import(sourcePath) { | |
copydir.sync(sourcePath, this.sourceDir); | |
} | |
// 向 pack 中单个或多个添加文件 | |
addFile(filePath, content) { | |
const paths = Array.isArray(filePath) ? filePath : [filePath]; | |
paths.forEach(filePath => { | |
const targetPath = path.join(this.sourceDir, filePath); | |
mkdirp.sync(targetPath.split('/').slice(0, -1).join('/')); | |
fs.writeFileSync( | |
targetPath, | |
typeof content === 'object' ? JSON.stringify(content) : content | |
); | |
}); | |
} | |
// 从 pack 中删除单个或多个文件 | |
dropFile(filePath) { | |
const paths = Array.isArray(filePath) ? filePath : [filePath]; | |
paths.forEach(filePath => { | |
const targetPath = path.join(this.sourceDir, filePath); | |
try { | |
const stat = fs.statSync(targetPath); | |
if (stat) { | |
fs.unlinkSync(targetPath); | |
} | |
} | |
catch (e) { | |
console.log(e); | |
} | |
}); | |
} | |
// 输出一个 zip 文件并返回输出地址 | |
output(filename = 'pack') { | |
const zipDir = path.join(this.outputDir, `./${filename}.zip`); | |
const output = fs.createWriteStream(zipDir); | |
const archive = archiver('zip', {zlib: {level: 9}}); // 压缩等级 | |
return new Promise((resolve, reject) => { | |
output.on('close', () => { | |
resolve(zipDir); | |
}); | |
archive.on('error', err => { | |
reject(err); | |
}); | |
archive.pipe(output); | |
archive.directory(this.sourceDir, filename); | |
archive.finalize(); | |
}); | |
} | |
// 删除源文件和输出的文件 | |
dispose() { | |
rmdir(this.baseDir, err => { | |
if (err) { | |
throw err; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment