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

209
Visualizações
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 Respostas
Responde à pergunta

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