我正在尝试将 MySQL 查询的输出动态写入存档。这是我的代码:
var async = require("async");
var mysql = require("mysql");
var express = require("express");
var archiver = require("archiver");
var app = express();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'test'
});
app.get('/file', (req, res) => {
res.writeHead(200, {
'Content-Type': 'application/zip',
'Content-disposition': 'attachment; filename=archive-name.zip'
var zip = archiver('zip', {
zlib: { level: 9 }
});
zip.pipe(res);
zip.on('end', function() {
console.log('Archive wrote %d bytes', zip.pointer());
});
const queriesArray = ["SELECT * FROM tb1", "SELECT * FROM tb2"];
async.forEachOf(queriesList, (query) => {
connection.query(query, (err, results) => {
if(!err) {
zip.append(JSON.stringify(results), {name: `${query}.txt`})
}
else {
console.log("Error while performing Query");
}
})
}, function(err) {
if (err) {
console.log("error")
}
else {
zip.finalize();
}
})
})
const port = process.env.PORT || 7000;
app.listen(port, () => {
console.log('Listen on port ' + port);
})
此代码应该创建一个包含多个文本文件的 zip 存档。用户访问/file
页面必须显示文件下载提示,但似乎zip.finalize()
无法正常工作,因此我无法下载创建的存档(在我访问时开始下载/file
但未完成)。为什么我的代码不起作用?