Home > other >  Node.js doesn't handle an error in express
Node.js doesn't handle an error in express

Time:11-12

I have this code:

const express = require("express");
const app = express();

var meetings = [];

app.use("/static", express.static("public/"))
app.use("/index.html?", function(request, response, next) {
    response.redirect("/");
})

app.get("/", function(request, response) {
    response.sendFile(__dirname   "/pages/index.html");
})

try {
    app.listen(80);
} catch(e) {
    console.log("Can't run on port 80. Please, run me as a sudo!");
}

When I run it, I got this error:

Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1361:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EACCES',
  errno: -13,
  syscall: 'listen',
  address: '0.0.0.0',
  port: 80
}

Node.js v17.0.1

When I'm running this as sudo, it doesn't find express module. What I'm doing wrong? Any help is appreciated.

CodePudding user response:

I think you can't catch it like that because app.listen() always return a <net.Server> instance. To catch an error on this instance you should look for the error event. So, this is how you would catch it.

const express = require("express");
const app = express();

var meetings = [];

app.use("/static", express.static("public/"))
app.use("/index.html?", function(request, response, next) {
    response.redirect("/");
})

app.get("/", function(request, response) {
    response.sendFile(__dirname   "/pages/index.html");
})


app.listen(80).on(error => { 
  if (error.code === "EACCESS") {
    console.log("Can't run on port 80. Please, run me as a sudo!");
  }
});
   
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

As for why it can't find express, is that I am guessing if you run it with sudo, it looks for globally installed modules. But this is just a guess because it runs fine when I run the same code with sudo on my machine.

  • Related