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.

5
  • 2
    You can’t listen on a port below 1024 without being root - they are historically “privileged ports”. Commented Nov 11, 2021 at 12:12
  • Does this answer your question? Node.js app can't run on port 80 even though there's no other process blocking the port Commented Nov 11, 2021 at 12:13
  • I want to handle an error Commented Nov 11, 2021 at 12:14
  • Which error did you want to handle? Commented Nov 11, 2021 at 13:35
  • I want to handle EACCES error Commented Nov 11, 2021 at 13:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.