Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.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
Javascript 如何使用docx包附加文件_Javascript_Node.js - Fatal编程技术网

Javascript 如何使用docx包附加文件

Javascript 如何使用docx包附加文件,javascript,node.js,Javascript,Node.js,我需要在我的服务器上有一个word文档。当有人点击保存按钮时,我需要将数据保存在文档中。我使用以下命令创建word文档。它为我创建了一个新文档,但我想将数据附加到现有文档中 const fs = require('fs'); const docx = require('docx'); let doc = new docx.Document(); let paragraph = new docx.Paragraph("welcome to my document

我需要在我的服务器上有一个word文档。当有人点击保存按钮时,我需要将数据保存在文档中。我使用以下命令创建word文档。它为我创建了一个新文档,但我想将数据附加到现有文档中

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

    let doc = new docx.Document();

    let paragraph = new docx.Paragraph("welcome to my document");

   //when client loads a new page and clicks save button             
    app.post('/newpg',(req,res)=>{


    paragraph.addRun(new docx.TextRun("Another line to be added"));

    doc.addParagraph(paragraph);

    **let packer = new docx.Packer();
    packer.toBuffer(doc).then((buffer)=>{
        fs.writeFileSync("sample.docx",buffer);
    });**

这段代码应该可以工作,它与您已经拥有的非常相似,我只是添加了响应和错误处理

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

let doc = new docx.Document();

let paragraph = new docx.Paragraph("welcome to my document");

//when client loads a new page and clicks save button             
app.post('/newpg', (req, res) => {

    paragraph.addRun(new docx.TextRun("Another line to be added"));

    doc.addParagraph(paragraph);

    let packer = new docx.Packer();
    packer.toBuffer(doc).then((buffer) =>{
        fs.writeFileSync("sample.docx",buffer);
        res.status(201).json({ status: "Doc updated"} );
    }).catch(err => {
        res.status(500).json({ status: "An error occurred updating document." });
    });
});