Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 下载时生成的docx为空_Node.js_Meteor_Download_File Generation - Fatal编程技术网

Node.js 下载时生成的docx为空

Node.js 下载时生成的docx为空,node.js,meteor,download,file-generation,Node.js,Meteor,Download,File Generation,这是一个流星应用程序。我需要生成一个docx文件并下载它。 我通过运行:localhost:3000/下载来测试它 Word文件已生成,但它完全为空 为什么??如果有任何建议,我将不胜感激 这是我的服务器端代码: const officegen = require('officegen'); const fs = require('fs'); Meteor.startup(() => { WebApp.connectHandlers.use('/download', function(

这是一个流星应用程序。我需要生成一个docx文件并下载它。 我通过运行:localhost:3000/下载来测试它

Word文件已生成,但它完全为空

为什么??如果有任何建议,我将不胜感激

这是我的服务器端代码:

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

    });
});

您面临的问题是docx.generate(out)是一个异步函数:当调用
res.end(docx.generate(out))
时,您立即结束请求,同时开始在文件
test.docx
中生成docx。因此,文档还不存在

您应该修改代码以直接通过文件发送,如下所示:

res.writeHead(200, {
    'Content-Disposition': `attachment;filename=${filename}`,
    'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  });
docx.generate(res)

如果您仍然需要服务器端的文件,您可以使用另一种方法等待生成文件()

Nice!你救了我一天!谢谢你,维克多!:)