0

I have a simple server:

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 EACCES error.

How to handle an exception? Any help is appreciated.

Vad Sim
  • 266
  • 8
  • 21

1 Answers1

2

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

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.