需求:将一些数据写入到json文件中将这些数据与对应的素材压缩后传到前端
1. 在数据库中查询到相应数据
const data = await this.models.data.findAll({
where: {
id: parseInt(id),
},
});
2. 构建目录
const promiseDirSync = function(dir = './test', mode) {
if (fs.existsSync(dir)) return;
promiseDirSync(path.dirname(dir), mode);
fs.mkdirSync(dir, mode);
};
// 构建压缩文件夹
await exportForImport({data});
3. 构建压缩文件夹
async exportForImport(params) {
// 设置各种路径
const testPath1 = path.join('./xx1/', 'xx/xx1'); // 需要压缩的目录
const testPath2 = path.join('./xx2/', 'xx/xx2'); // 素材目录
const testPath3 = path.join('./xx3/', 'xx/xx3'); //
// ...
// 定义文件复制函数
const copyDirSync = function(dir, target) {
// 如果目标目录不存在,创建
if (!fs.existsSync(target)) {
fs.mkdirSync(target);
}
const files = fs.readdirSync(dir); // 同步拿到文件目录下的所有文件名
files.forEach(function(item) {
const itemPath = path.join(dir, item);
const targetPath = path.join(target, item);
const stat = fs.statSync(itemPath);
if (stat.isFile()) {
fs.copyFileSync(itemPath, targetPath);
} else {
copyDirSync(itemPath, targetPath);
}
});
};
// 复制文件
rmDirSync(testPath1);
if (fs.existsSync(testPath2)) copyDirSync(testPath2, testPath1);
else promiseDirSync(testPath1);
// 写入数据
const configPath = path.join(testPath1, 'config.json');
fs.writeFileSync(configPath, JSON.stringify(params, undefined, 2));
}
压缩文件并传给前端
const distPath = path.join('xx/');
const filePath = path.join(xx/xx.xx);
await tar.c(
{
gzip: true,
file: filePath,
cwd: distPath,
},
fs.readdirSync(distPath)
);
ctx.attachment(`xx.xx`);