0

I am trying to refactor docxtemplater code out of my server file in node. The req.body json object works fine there, and even can be console.logged inside the doc.setData() method. However when I try to run the server I am getting this error:

firstName: data.firstName,
               ^      
TypeError: Cannot read property 'firstName' of undefined     

This is my docxtemplater.js file.

const express = require('express');
const Docxtemplater = require('docxtemplater');
const JSZip = require('jszip');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

function estateDoc (data) {

let content = fs.readFileSync(path.resolve(__dirname, 'docxGen.docx'), 'binary');

let zip = new JSZip(content);

let doc = new Docxtemplater();
doc.loadZip(zip);

doc.setData({
  firstName: data.firstName,
  lastName: data.lastName,
  middleName: data.middleName,
  suffix: data.suffix,
  socialSecurity: data.socialSecurity,
  address: data.address,
  telephone: data.telephone,
  heir: data.heir
});
  try {
      doc.render()
  }
  catch (error) {
      var e = {
          message: error.message,
          name: error.name,
          stack: error.stack,
          properties: error.properties,
      }
      console.log(JSON.stringify({error: e}));
      throw error;
  }
  var buf = doc.getZip()
               .generate({type: 'nodebuffer'});
  fs.writeFileSync(path.resolve(__dirname + '/doc-sender-catcher', 'output.docx'), buf)
};
estateDoc();

module.exports = {estateDoc};
John
  • 1,075
  • 1
  • 7
  • 13

1 Answers1

0

So I'm leaving this here for anyone new to refactoring in node. Don't declare your function and then call it before you export and run it. My problem was the last line where I was running the function with the data argument empty...

John
  • 1,075
  • 1
  • 7
  • 13