MongoDB,Express,Angular,and Node.js Fundamentals
上QQ阅读APP看书,第一时间看更新

Getting Started with Node

Here, we will build on the introduction to Node from the previous topic and concretize our knowledge about Node by completing exercises and activities that will help us understand how application development with Node.js is achieved. To get started with Node.js, the first step is installation. You have two installation options: the LTS or stable version:

LTS (Long Term Support): Support and maintenance are provided by the Node foundation for at least 18 months since the date of release. So, it's better to use this version for the production of backend Node applications.

Stable: Stable will have support for approximately 8 months after release, with features/updates released more often. This version can be used for production if you're using Node for frontend services (dependency management). If apps can be easily updated without interrupting the environment, this version will work for backend services in Node as well. In this book, we will be using the LTS version.

Before we start with Node application development, we need to understand the built-in modules that make up Node. The set of modules that you can use without any further installation are listed as follows, along with a short description:

  • Assert: This module provides a set of assertion tests
  • Buffer: This module is used to handle binary data
  • Child process: This module is used to run a child process
  • Cluster: This module is used to handle unhandled errors
  • Events: This module is used to handle events
  • Filesystem (fs): This module is used to handle the filesystem
  • HTTPS: This module is used to render Node as an HTTPS server
  • Path: This module is used to handle file paths
  • Readline: This module is used to handle readable streams one line at the time
  • Stream: This module is used to handle streaming data
  • String: This module is a decoder that's used to decode buffer objects into strings
  • Timers: This module is used to execute a function after a given number of milliseconds

Beginning a node application involves the following steps:

  1. Importing and loading the required modules by invoking the "require" directive.
  2. Creating the server that will receive the client's requests.
  3. Reading the requests and returning the responses from the server that was created in the preceding step.

We will apply all of these steps in our first exercise.

Exercise 1: Creating Our First Node Program

Before beginning this exercise, make sure you have Node installed. Our aim is to create a Node.js program that will print "Hello World" on the browser window once the appropriate command is passed onto the server. To do so, the following steps have to be performed:

Note

The code files for this exercise can be found here: https://bit.ly/2sfCGTD.

  1. Create a JavaScript file and name it hello.js. This can be done using the options in the File tab.
  2. Load the built-in module http by using the "require" directive and passing a constant variable ('http') to it:

    const http = require ('http');

  3. Declare and initialize the hostname and port as constant variables using the following code:

    const hostname = '127.0.0.1';

    const port = 8000;

  4. Create the server using the createServer method and pass req and res, which denote a request to and a response from the server, respectively:

    const server = http.createServer((req, res) => {

    res.statusCode = 200;

    res.setHeader('Content-Type', 'text/plain');

    res.end('Hello World\n');

    });

    This created server sends the following response to the browser:

    statusCode: 200, the Content-Type header in plain text, and a string, "Hello World."

  5. Have the server listen to localhost on port 8000 using the following command:

    server.listen(port, hostname, () => {

    console.log ('Server running at

    http://${hostname}:${port}/');

    });

  6. Run the server using the following command prompt, as shown in the following screenshot:

    node hello.js

Figure 1.3: Running the server using the command prompt

The output is as follows:

Figure 1.4: Output of the hello.js program

One of the learning objectives of this book is to create the components of a blogging application with basic features. We will commence its development from this chapter. Most of this will be done in the activity section of each topic.

Activity 1: Creating an HTTP Server for a Blogging Application

Note

The code files for this activity can be found here: https://bit.ly/2H0d2fL.

You have been tasked with developing the HTTP server component for a blogging application. Your aim is to call the server and listen to the localhost on a specified port. Before you begin this activity, ensure that you have completed the previous exercise in addition to creating a project directory named Blogging Application and a subfolder named Server. You can use an IDE of your choice; however, in this book, we are using Visual Studio.

To complete this activity, the following steps have to be completed:

  1. Create a server.js file.
  2. Declare and assign the HTTP server.
  3. Declare and assign localhost and port number.
  4. Create an HTTP server.
  5. Listen to the Server.
  6. Run the Server.js file on the command-line terminal.
  7. Go to your browser and type in the address localhost:8000.

    Note

    The solution for this activity can be found on page 228.