Home > Enterprise >  NodeJS: Server.on-listenerfunction doesn't exist when exporting?
NodeJS: Server.on-listenerfunction doesn't exist when exporting?

Time:08-07

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);
})

CodePudding user response:

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.

  • Related