【发布时间】:2016-12-14 02:15:25
【问题描述】:
我正在使用 Node.js 构建一个 Web 应用程序,现在我需要生成 PDF 目录的 tar 存档。该应用程序在运行 Ubuntu 14.04 服务器的 VM 上运行。我的代码如下所示:
function tarDirectory(path, token, callback) {
var exec = require('child_process').exec;
var cmd = 'cd ' + path + ' && tar -cvf genericName-' + token + '.tar' + ' ' + token;
exec(cmd, function(error, stdout, stderr) {
console.log(stdout);
console.log(stderr);
if (error) {
console.error(error);
}
if(callback) callback();
});
}
这个 tarDirectory 函数由以下代码调用:
router.post('/files/generate', function(req, res, next) {
IDList = req.body['IDs[]'];
token = req.body['token'];
// if just a single file being generated
if (typeof req.body['IDs[]'] === "string"){
filehelper.generateFile(IDList[0], req.app.locals.site.basedir + "temp/", token);
}
// if multiple files being generated
else {
IDList.forEach(function(id) {
filehelper.generateFile(id, req.app.locals.site.basedir + "temp/", token);
});
}
filehelper.tarDirectory(req.app.locals.site.basedir + "temp/", token, res.end);
});
代码需要一个带有动态数据的发布请求,该请求是通过在我的网络应用程序中单击按钮生成的,然后将基于数据创建文件并将其 tar 到一个目录中。这一切都很好……第一次。当我第一次单击该按钮时,会生成 tar,当我打开它时,客户端 PDF 与服务器上的 PDF 相同。但是,当我在大约一个小时内再次单击时,我会收到一个 tar 文件,但是当我打开存档并解压缩它时,PDF 全部损坏并且大约是预期字节大小的一半。我在这里不知所措...我怀疑这可能与对流关闭的不当处理有关,但我不确定。
这是将 PDF 生成到目录中的代码,然后在生成后将其打包:
function generateFile(id, path, token) {
var dirPath = path + token;
var filePath = path + token + "/file" + id + ".pdf";
console.log("creating file for: " + id);
try{
fs.statSync(dirPath).isDirectory();
} catch (err) {
fs.mkdirSync(dirPath);
}
// start the file pdf generation
file = new PDFDocument();
output = fs.createWriteStream(filePath);
output.on('close', function(){
return;
});
file.pipe(output);
// handle the intricacies of the file generation
file.text("file" + id + ".pdf");
// end the file
file.end();
}
【问题讨论】: