Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
How to add variables and methods in callback parameters

I'm making a custom middleware package as a project, and I ran into a problem. In one of the files, I have some jsdoc types (trying to make the package small so no typescript) for the callback:

class Response {
  constructor() {
    // Constructor stuff
  }
  /**
   * 
   * @param {string} path 
   */
  async useFile(path, file) {
    const res = await fetch(path, {
      method: 'GET',
      body: fs.readFile(file, (err, data) => {
        if (err) throw err
        else return data
      }),
      headers: {
        'Content-type': 'text/html'
      }
    })
    return JSON.stringify(res)
  }
}

I then import that Response class and use it as a type:

server.get('/', (req, res) => {
  res.useFile('index.html')
})

In my test folder, I'm creating a server and assigning it to this server variable. I then call the get method, using the useFile method on the response:

server.get('/', (req, res) => {
  res.useFile('index.html')
})

But when I run the code get this error:

res.useFile('/', './index.html')
      ^

TypeError: Cannot read properties of undefined (reading 'useFile')

I know that the res param is undefined (because it's a parameter), so the useFile method won't work, but I've seen other middleware packages like express do this without problems. How do I put these methods onto the params?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda