js docx报错Packer.toBuffer error in browser: nodebuffer not supported by this platform解决方法

docx是一个使用JS/TS轻松生成和修改docx word文件的开源库,适用于Node环境和浏览器环境。

Github地址:https://github.com/dolanmiu/docx

官网地址:https://docx.js.org/#/

按照官网demo写法,保文件时报错:

Packer.toBuffer error in browser: nodebuffer not supported by this platform

代码如下:

import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "docx";

// Documents contain sections, you can have multiple sections per document, go here to learn more about sections
// This simple example will only contain one section
const doc = new Document({
    sections: [
        {
            properties: {},
            children: [
                new Paragraph({
                    children: [
                        new TextRun("Hello World"),
                        new TextRun({
                            text: "Foo Bar",
                            bold: true,
                        }),
                        new TextRun({
                            text: "\tGithub is the best",
                            bold: true,
                        }),
                    ],
                }),
            ],
        },
    ],
});

// Used to export the file into a .docx file
Packer.toBuffer(doc).then((buffer) => {
    fs.writeFileSync("My Document.docx", buffer);
});

// Done! A file called 'My Document.docx' will be in your file system.

解决方法:把Packer.toBuffer换成Packer.toBlob,直接回调里返回blob二进制流。参考:

Packer.toBlob(doc).then((blob) => {
	saveAs(blob, title + '.doc');
});

其中,saveAs是开源库file-saver里面的方法。当然此处也可以使用其他方法保存文件至本地。

参考资料:https://github.com/dolanmiu/docx/issues/2422