The Demo App: Setup

We will build a server application in NodeJS using Express framework.

The app is striped down to minimally required components; it must not be taken as an example of good practices. Namely, there is no persistence; this is deliberate to keep things simple.

  • Install NodeJS, the JavaScript runtime environment, for your operating system (if not already installed). The installer will also install NPM (node package management) tool. You can verify the installation by opening the terminal and checking the version of node and npm

    node -v
    npm -v
    
  • Create a folder where you want to store the source code of this demo app. I'm going to call this folder app-folder. Open the terminal, change directory to app-folder. Type in the following command

    npm init -y
    

    The command will create a file package.json in your app-folder. Feel free to checkout the content of this file.

  • Next, key in the following command to install ExpressJS as a dependency of your app.

    npm install --save express
    

    Express is a minimalist web framework for NodeJS.

  • Create a file index.js in your app-folder and copy the following code snipped into it

    const express = require("express");
    
    // Initialize express.
    const app = express();
    
    // Set up port.
    const port = process.env.PORT || 7000;
    
    // Set up homepage route
    app.get("/", (req, res) => {
      res.send("Test Home Page!");
    });
    
    // Start the server.
    app.listen(port, () => {
      console.log(`Listening on http://localhost:${port}/`);
    });
    

    The code is self explanatory (if you have created web servers before); it sets up a server that listens to requests on localhost port 7000.

  • Head over to the terminal and run the server

    node index.js
    

    Your app must be running at http://localhost:7000/.