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

216
Vistas
NodeJS: Server.on-listenerfunction doesn't exist when exporting?

I am using server.js to start the server and router.js to listen to the requests. When I try to access the server, nothing happens and I can't reach it, I assume so, because the server.on function doesn't execute. Everything works, when I put it just in the server.js tho, so the error seems to be in with the exports/imports, but I can't figure out what it is.

server.js:

const fs = require("fs");
const http = require("http");
const template = require("./template.js");

const port = 3000;

const server = http.createServer();

server.listen(port, () => {
    console.log(`Server listening on localhost:${port}`);
})

module.exports = server;

router.js:

const server = require("./server.js");
const template = require("./template.js");

server.on("request", (req, res) => {
    let url = req.url;
    let method = req.method;
    let html;
    console.log("received req");
    res.writeHead(200, { "content-type": "text/html; charset=utf-8" });

    if(url.endsWith("/feedback") && method == "GET") {
        html = template.createHtml("Liste der Feedbacks");
    } else {
        html = template.createHtml(`Methode: ${method}, URL: ${url}`);
    }

    res.end(html);
})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you are looking to import the router.js and have the server object accessible in that file and execute the on method on it, one way to do it is by passing the server while requiring the router.js file as follows:

server.js:

const fs = require("fs");
const http = require("http");
const port = 3000;

const server = http.createServer();

const router = require("./router.js")( server );

server.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}`);
});

router.js:

const template = require("./template.js");

module.exports = function handleRequest( server ){
    return server.on("request", (req, res) => {
        let url = req.url;
        let method = req.method;
        let html;
        console.log("received req");
        res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
    
        if(url.endsWith("/feedback") && method == "GET") {
            html = template.createHtml("Liste der Feedbacks");
        } else {
            html = template.createHtml(`Methode: ${method}, URL: ${url}`);
        }
    
        res.end(html);
    })
}

Whatever pattern you try, make sure to avoid Circular dependencies.

Also, as a general recommendation, I would suggest that you try and avoid tight coupling in modules such as these whenever possible. Ideally, the router module should not be tightly coupled to the server module.

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