[Solved] Generated docx is empty when downloaded

Hi

I am quite newbie in this topic.
I need to generate a docx-file and download it.
This is my server code. I am testing it by running: localhost:3000/download.
Word file is generated, but it is totally empty.
Why? I would appreciate any advice! :slight_smile:

const officegen = require('officegen');
const fs = require('fs');

Meteor.startup(() => {

WebApp.connectHandlers.use('/download', function(req, res, next) {

    const filename = 'test.docx';
  
    let docx = officegen('docx')

    // Create a new paragraph:
    let pObj = docx.createP()

    pObj.addText('Simple')
    pObj.addText(' with color', { color: '000088' })
    pObj.addText(' and back color.', { color: '00ffff', back: '000088' })

    pObj = docx.createP()

    pObj.addText(' you can do ')
    pObj.addText('more cool ', { highlight: true }) // Highlight!
    pObj.addText('stuff!', { highlight: 'darkGreen' }) // Different highlight color.
    
    docx.putPageBreak()
    
    pObj = docx.createP()
            
    let out = fs.createWriteStream(filename);
    
    res.writeHead(200, {
        'Content-Disposition': `attachment;filename=${filename}`,
        'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      });
    
    res.end(docx.generate(out));

    });
});

I think this lib create office files on disk only. Do you need read this file after save to send to browser download.

Check if your file is been created on filesystem. If yes, you can read it and download.

Warning: docx.generate() is a async method.

1 Like

Thanks raragao for your advice!

I found the solution.

The problem was in the last line:

res.end(docx.generate(out));
must be
docx.generate(res);

So the correct generated file now can be opened in the browser! Yes! :slight_smile: