CSE 340: Web Backend Development

W01 Learning Activity: Node.js

Overview

In previous activities you learned more about JavaScript and the principles of server-side web development. In this activity you will learn about Node.js, the server application you will be using throughout the course. You will learn how to setup Node.js to run on your local machine.

Activity Instructions

Complete each of the following steps to set up a Node.js server on your computer.

Install Node.js and NPM

If you have not already done so, you must install Node.js and NPM (the Node Package Manager). This was covered previously in the W01 Setup: Tools activity.

Open VS Code and navigate to your project directory

In the W01 Setup: Tools activity you should have created a new repository for this course and cloned it to your computer. If you have not done this yet, stop and complete this task before continuing.

  1. Open VS Code.
  2. Select File > Open Folder... from the menu.
  3. Navigate to the folder where you cloned your course repository and select it.
  4. Open a new terminal in VS Code by selecting Terminal > New Terminal from the menu. This will open a terminal window at the bottom of VS Code.

Verify your .gitignore file

Before proceeding, make sure your project folder contains a file named .gitignore. This file tells Git which files and folders to ignore when you make commits to your repository. It is important to ensure that certain files, such as node_modules and environment variable files, are not included in your repository.

  1. In the VS Code file explorer, look for a file named .gitignore in the root of your project folder.
  2. If the file does not exist, create a new file named .gitignore in the root of your project folder (notice the dot "." at the beginning of this filename).
  3. Verify (or add if they are not present) the following lines to your .gitignore file:
    node_modules/
    .env
    
  4. Save the .gitignore file.

Create your first Node.js application

As mentioned previously, Node.js is the server application you will run to listen for requests and send back responses.

Create a new node application in your project folder by completing the following steps:

  1. In the terminal, run the command npm init to create a new package.json file. This package.json file defines your node application. You can press the Enter key to accept the default values for each prompt except for the following:
    • When prompted for the entry point, enter server.js instead of the default index.js.
    • When prompted for the type, enter module instead of the default commonjs.
  2. Create a new file named server.js in the root of your project folder.
  3. Add the following code to server.js:
    console.log("Hello, Node.js!");
    
  4. Run your server.js program, by typing the following at the terminal: node server.js . You should see the text, "Hello, Node.js" display at the terminal.

At this point, your program is just like a Python program or anything else that you may have written, it simply runs code and displays a result. The next step is to make your program list for HTTP requests so that it works as a web server.

Complete the following steps to import the Express library and use it to listen for HTTP requests.

  1. Install the Express framework by running the command npm install express. This will download the express library from the node package repository, and it will add it to your package.json file, to indicate that your application depends on this library.
  2. Update your server.js file to replace the previous code with the following:
    import express from 'express';
    
    const NODE_ENV = 'production';
    const PORT = 3000;
    
    const app = express();
    
    app.get('/', (req, res) => {
      res.send('Hello from Express!');
    });
    
    app.listen(PORT, () => {
      console.log(`Server is running at http://127.0.0.1:${PORT}`);
      console.log(`Environment: ${NODE_ENV}`);
    });
    
  3. Run your server.js program again by typing the following at the terminal: node server.js . You should see the text, "Server is running at http://127.0.0.1:3000" display at the terminal.
  4. Open a web browser and navigate to http://127.0.0.1:3000. You should see the text, "Hello from Express!" displayed in the browser.
  5. When you are ready to stop your server, in the terminal, press Control C to break or stop the process.

This is amazing! With just those few lines of code, you have created a simple web server!

What is happening here?

Consider the following lines of code:

import express from 'express';

...

const app = express();

These lines import the Express library and create a new Express application instance. Throughout the rest of this file, you will use the variable app to use many things from the framework.

Consider the following lines of code:

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

These lines define a route handler for GET requests to the root URL ("/"). When a user navigates to this URL in their browser, the server responds with the text "Hello from Express!". The req parameter represents the incoming request, and the res parameter is used to send a response back to the client.

You will learn how to do many more things with these route handlers in later activities.

Consider the following lines of code:

app.listen(PORT, () => {
  console.log(`Server is running at http://127.0.0.1:${PORT}`);
  console.log(`Environment: ${NODE_ENV}`);
});

These lines start the server and make it listen for incoming requests on the specified port (3000 in this case). When the server is successfully started, it logs a message to the console indicating that it is running and provides the URL where it can be accessed.

Make sure these steps work before moving on

It is very important to make sure your server is working and listening for requests at this point. If it is not, you should stop here and resolve the problem before moving on.

Please post any questions or problems you have to the course Microsoft Teams channel.

Optional Video Walkthrough

While the following video may be helpful to see the steps in action, make sure to walk through the written instructions directly because there may be important steps that are not covered in the video.

Direct link: Your First Node.js Application

Install Nodemon for Development

When you are developing your Node.js application, it is helpful to have the server automatically restart whenever you make changes to your code. This saves you from having to manually stop and restart the server each time you make a change.

To accomplish this, you will install a tool called nodemon. Nodemon is a utility that monitors for any changes in your source code and automatically restarts your Node.js application.

Complete the following steps to install and configure nodemon:

  1. Install nodemon as a development dependency by running the following command in your terminal: npm install --save-dev nodemon . (The save-dev flag adds this to a list of dependencies for development only, because it will not be needed in the production environment.)
  2. Create a new file nodemon.json and copy the following configuration settings into this file to tell node the starring command to execute and which file extensions should trigger an update:
    {
        "ext": "js css ejs env",
        "exec": "node server.js",
        "ignore": [
            ".git",
            "node_modules"
        ]
    }
    
  3. Update your package.json file to add a new script for starting your server in development mode. Replace your scripts section with the following:
    "scripts": {
      "dev": "nodemon",
      "start": "node server.js"
    },
    

    This adds a new script named dev that uses nodemon to start your server. The start script will run node as normal for production use.

  4. Now, instead of running your server with node server.js, you start it in development mode by running the command: npm run dev . (If you would like to run it in production mode, you run the command: npm run start .)
  5. Run your application by typing npm run dev in the terminal. Then, with nodemon running, try making a change to your server.js file (for example, change the response text in the route handler). Save the file, and you should see nodemon automatically restart the server in the terminal.
  6. Refresh your web browser to see the changes reflected.

Optional Video Walkthrough

While the following video may be helpful to see the steps in action, make sure to walk through the written instructions directly because there may be important steps that are not covered in the video.

Direct link: Dev Tool: Nodemon

Add Environment Variables

Environment variables allow you to store configuration settings outside of your code, making it easier to manage different settings for development and production environments.

In the case of your application, you will have a set of variables to use when it is running on your computer, and a different set to use when it is running in the cloud. Environment variables are the perfect way to store those variables so that the source code can be the same in both cases, but the app can behave differently based on these variables.

Complete the following steps:

  1. Create a new file named .env in the root of your project folder.
  2. Add the following code to the .env file:
    PORT=3000
    NODE_ENV=development
    
  3. Update your server.js file to include the following code right after the import statement.

    Replace these lines of code:

    const NODE_ENV = 'production';
    const PORT = 3000;
    

    With these lines of code:

    // Define the the application environment
    const NODE_ENV = process.env.NODE_ENV?.toLowerCase() || 'production';
    
    // Define the port number the server will listen on
    const PORT = process.env.PORT || 3000;
    
  4. Notice that these lines of code try to get the value from the environment variable first, but then fall back to other hardcoded values ('production' and 3000) if the environment variables are not found.

  5. In order for your Node.js server to get the information from your .env file, you need to pass that file to it when you start the server. Update your nodemon.json file. Change the "exec": "node server.js", line to be the following:
    "exec": "node --env-file=.env server.js",

    This ensures that when the server is run in development mode, the .env file will be passed to it.

  6. Run your application again by typing npm run dev in the terminal.
  7. Verify that it displays on the console:
    Server is running at http://127.0.0.1:3000
    Environment: development
    

    If your console says "Environment: production" it is not correctly reading in the information from your .env file.

Optional Video Walkthrough

While the following video may be helpful to see the steps in action, make sure to walk through the written instructions directly because there may be important steps that are not covered in the video.

Direct link: Environment Variables

Complete Code Files (Click to expand)

The following are the complete files at this point:

server.js

import express from 'express';

// Define the the application environment
const NODE_ENV = process.env.NODE_ENV?.toLowerCase() || 'production';

// Define the port number the server will listen on
const PORT = process.env.PORT || 3000;

const app = express();

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.listen(PORT, () => {
  console.log(`Server is running at http://127.0.0.1:${PORT}`);
  console.log(`Environment: ${NODE_ENV}`);
});

.env

PORT=3000
NODE_ENV=development

nodemon.json

{
    "ext": "js css ejs env",
    "exec": "node --env-file=.env server.js",
    "ignore": [
        ".git",
        "node_modules"
    ]
}

package.json (The text [your repo here] should contain your actual GitHub repository. And the versions of libraries may be slightly different for you.

{
  "name": "cse340-hw",
  "version": "1.0.0",
  "description": "",
  "homepage": "[your repo here]",
  "bugs": {
    "url": "[your repo here]"
  },
  "repository": {
    "type": "git",
    "url": "git+[your repo here]"
  },
  "license": "ISC",
  "author": "",
  "type": "module",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js",
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^5.2.1"
  },
  "devDependencies": {
    "nodemon": "^3.1.11"
  }
}

Submission

After you have completed all the learning activities for this lesson, return to Canvas to submit a quiz.

Other Links: