01 Project – Node.js / Express / MongoDB – Part 03 – Booting up the application

Before booting up the application for the first time we have to set up a few more things in our index.js file.

app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');

The process.env.PORT is a constant. This built-in Node.js constant is an environment setting that sets the port value to the server.
The second line sets the location of our HTML templates (which are called “views”) to the /views folder from within the current working directory.

Now we have to create the HTTP server and tell it to listen for connections. We can do that easily using our app object.

First we create our first route, the route to the home page. Now it is set to display a message.

app.get('/', function(req, res){
  res.send('There is nothing to show yet');
});

Below, the code calls the listen() function on our app that tells it which port to listen to. Once the server is up and running, an anonymous function is triggered in order to display a message.

app.listen(app.get('port'), function{
  console.log('Server up: http://localhost: ' + app.get('port'));
});

Now, we need to see if everything works!
Open the terminal and run the command node index.js. Once the server is up, you can check the browser by visiting http://localhost:3300. Everything works as it is supposed to!

Booting up Node.js server

Leave a Reply