Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Writing to a XLSX template and then sending it as a response in a different function, always returns undefined

What I'm trying to do

Requests come into my server to download a file containing data. The downloading part is in the front-end and works. I grab the data on my backend and then I want to write it into an existing template and return the data.

This is the handler for the request.

async handle(request: Request, response: Response) {

    try {

      const fileName = 'test.xlsx'
      const binary = objectsToTemplateWorkBook()

      response.setHeader(
        'Content-Disposition',
        'attachment; filename=' + fileName
      )

      response.setHeader('Content-Type', 'application/vnd.openxmlformats')
      response.end(binary, 'binary')
    } catch (error) {
      console.log(error)
      response.send(error)
    }
  }

This is the function that is supposed to write the data into the template.

export const objectsToTemplateWorkBook = (): 
Promise<any> => {
  var XlsxTemplate = require('xlsx-template')
  var dataBlob
  // Load an XLSX file into memory
  const blob = fs.readFile(
    path.join(__dirname, 'test_template.xlsx'),
    function (err, data) {
      console.log(__dirname)
      // Create a template
      var template = new XlsxTemplate(data)

      // Replacements take place on first sheet
      var sheetNumber = 1

      // Set up some placeholder values matching the placeholders in the template
      var values = {
        people: [
          { name: 'John Smith', age: 20 },
          { name: 'Bob Johnson', age: 22 },
        ],
      }

      // Perform substitution
      template.substitute(sheetNumber, values)

      // Get binary data
      dataBlob = template.generate()
      // ...
    }
  )
  return dataBlob
}

The function seems to write the data to the template because if I log the dataBlob inside the fs.Readfile method it shows me the file. However, the return dataBlob always returns undefined. I know this is due to the async nature, but I have no idea how to fix it quite honestly. So my question to you is: how can I get the dataBlob to my handler to send it as a response?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!