0

我在 nodejs 中有一个用于生成文档的方法。如果我有两个同时请求,则一个文档的内容与第二个文档的内容相同(下面的变量“contents”)。例如,如果第一个请求检索到的 source.content 应该是“aaa”而第二个是“bbb”,那么在这两种情况下文件的实际内容都是“aaa”。如果请求是按顺序运行的,则生成的文件的内容是正确的,第一个请求为“aaa”,第二个请求为“bbb”。

public async generateDocument(req: Request, res: Response) {

        const sourceId = parseInt(req.params.id, 10);
        const source: ISource = await this.db.models.MoM.scope("full").findOne({ where: { sourceId : sourceId } });

        const signatureDate = getDateNow();
        // Load the docx file as a binary
        const content = fs.readFileSync(path.resolve(__dirname, "../../../../assets/Template.docx"), "binary");
        const zip = new PizZip(content);
        const doc = new Docxtemplater();
        doc.loadZip(zip);
        doc.setData({

            // @ts-ignore TODO: fix generic interfaces
            writer_name: "" + source.writer.displayedName,
            contents: source.content.split("\n").map((paragraph: string) => ({
                paragraph,
            })),

        });
        doc.render();
        const buf = doc.getZip().generate({ type: "nodebuffer" });
        const outputFilePath = path.resolve(__dirname, "../../../../assets/output.docx");
        fs.writeFileSync(outputFilePath, buf);
}
4

1 回答 1

0

在您的代码中,您可以在函数的末尾

const outputFilePath = path.resolve(__dirname, "../../../../assets/output.docx");
fs.writeFileSync(outputFilePath, buf);

这意味着如果函数被调用两次,则无法知道生成的文件是来自第一次调用还是第二次调用。

可能在您的代码中的某处,您正在阅读 /assets/output.docx 文件。

为了解决您的问题,我将改为从 generateDocument 函数返回一个 Buffer ,如下所示:

public async generateDocument(req: Request, res: Response) {
        // ...
        // ...
        doc.render();
        const buf = doc.getZip().generate({ type: "nodebuffer" });
        return buf;
}

并且 generateDocument 的调用者应该为缓冲区提供服务或对此做一些事情(例如,如果您只想让用户立即下载它,则无需将文件写入文件系统)。

于 2021-04-07T20:29:25.557 回答