我想使用officegen npm模块创建一个单词(docx)文件并下载它。在过去,我使用了tempfile模块来创建用于下载目的的临时路径。这是我为word doc download编写的代码:
var tempfile = require('tempfile');
var officegen = require('officegen');
var docx = officegen('docx');
router.post('/docx', function(req, res){
var tempFilePath = tempfile('.docx');
docx.setDocSubject ( 'testDoc Subject' );
docx.setDocKeywords ( 'keywords' );
docx.setDescription ( 'test description' );
var pObj = docx.createP({align: 'center'});
pObj.addText('Policy Data', {bold: true, underline: true});
docx.on('finalize', function(written) {
console.log('Finish to create Word file.\nTotal bytes created: ' + written + '\n');
});
docx.on('error', function(err) {
console.log(err);
});
docx.generate(tempFilePath).then(function() {
res.sendFile(tempFilePath, function(err){
if(err) {
console.log('---------- error downloading file: ' + err);
}
});
});
});
然而,它给我一个错误说
TypeError:dest.on不是函数
创建的总字节数也显示为0.我做错了什么?
答案 0 :(得分:3)
router.post('/docx', function(req, res){
var tempFilePath = tempfile('.docx');
docx.setDocSubject ( 'testDoc Subject' );
docx.setDocKeywords ( 'keywords' );
docx.setDescription ( 'test description' );
var pObj = docx.createP({align: 'center'});
pObj.addText('Policy Data', {bold: true, underline: true});
docx.on('finalize', function(written) {
console.log('Finish to create Word file.\nTotal bytes created: ' + written + '\n');
});
docx.on('error', function(err) {
console.log(err);
});
res.writeHead ( 200, {
"Content-Type": "application/vnd.openxmlformats-officedocument.documentml.document",
'Content-disposition': 'attachment; filename=testdoc.docx'
});
docx.generate(res);
});