MSK
MSK

Reputation: 69

how to append a file using docx package

i need to have a word doc in my server . when ever somebody clicks on the save button i need to save the data in the document . i use the following to create a word doc. it creates a new doc for me but i want to append the data to the existing document .

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

Upvotes: 1

Views: 1145

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

This code should work, it's very similar to what you have already, I've simply added response(s) and error handling.

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." });
    });
});

Upvotes: 1

Related Questions