2017-02-15 15 views
0

Я хочу использовать модуль officegen npm для создания файла word (docx) и загрузить его. В прошлом я использовал модуль tempfile для создания временного пути для загрузки цели. Вот код, который я написал для слова док загрузки:Node.js с помощью officegen для создания и загрузки документа Word

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 is not a function

общее число байтов, созданных также показаны 0. Что я делаю не так?

+1

Если вы используете новейший офис, тогда выход должен быть файловым потоком, а не только файлом. Обратитесь к руководству https://github.com/Ziv-Barber/officegen. Также вы можете напрямую генерировать ответ, например 'docx.generate (res);' – Andrey

+0

@Andrey thanks. Я сделал doc.generate (res), и он сработал. Ценю вашу помощь – codeinprogress

ответ

2
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); 
});