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

241
Visualizações
How to use one function within multiple files in node.js

So i have this one function which i am defining in my checkIfLogin.js

    function authCheck (req, res, next) {
      if (req.session.loggedin) {
          next();
      } else {
          res.render('login.ejs')
     }
  }

I want to use this function for e.g. in my dashboard.js, and clients.js page as well. How can i export function from one page and use it in ALL pgaes in my app. I have a main index.js file within my root dir that hosts all the imported files, but how can i import something like this to use the function within ALL files in my project?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use modules:

Export your function in checkIfLogin.js:

exports.authCheck = function authCheck (req, res, next) {
  if (req.session.loggedin) {
    next();
  } else {
    res.render('login.ejs')
  }
}

Import your function in otherFile.js:

var authCheck = require('./checkIfLogin.js').authCheck;

The string in require is your file path.

another approach

if you want to call this function before or after any api route you can use middleware

express middleware

about 4 years ago · Juan Pablo Isaza Relatório
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