What is the function of app.listen in Express?

2

Recently I started my studies in NodeJS and Express. From what I've been reading, app.listen, basically, is what makes the server listen for requests coming from the defined port.

But I noticed that when running an application in Express it runs normally even though there is no port listening statement. In the case, does the expression execute it under the cloths or something of the type? Maybe I'm asking silly, but I found nothing on the internet that would cure my doubt.

This is scaffold generated by express. As the code shows, it does not have any listener, but it works and processes the requests normally received.

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
    
asked by anonymous 14.08.2017 / 19:52

1 answer

2

The app.listen() function of Express starts a UNIX socket and listens for connections in a given path.

The app.listen(port, [hostname], [backlog], [callback]) function of Express is the same http.server.listen([port][, hostname][, backlog][, callback]) of the Node. According to the Node documentation, if no port is passed as a parameter, a random port will be used.

Omit the port argument, or use the port value of 0, to have the operating system assigned to random port , which can be retrieved by using server.address().port after the 'listening' event has been emitted.

const express = require('express')()

express.listen(undefined, 'localhost');

express.get('/', function (req, res) {
  res.send('Hello World!')
})

Will start a server without a specific port. Because of the Node (not Express), a random port is defined.

That is, you can start Express without specifying a port, but you can not start Express without telling you where to listen.

In my tests, every time I tried to start Express without app.listen it immediately quits.

In this case, you can check if the app is not running in the background already.

To check which port the Node is listening to:

lsof -i | grep node

It will return something like this:

node ... TCP localhost:57466 (LISTEN)

    
16.08.2017 / 05:12