Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda