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

238
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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