Introduction to Node.js — Create Your First Web App
Tags: node, webdev, javascript, beginners
Published: 2020-01-26 02:32:03

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

**Follow me on Twitter at https://twitter.com/AuMayeung**

**Many more articles at https://medium.com/@hohanga**

**Even more articles at http://thewebdev.info/**

[Node.js](https://nodejs.org/) is a run time platform to run server-side apps in JavaScript. It adopted the V8 browser engine to interpret JavaScript code on the server. It comes with its own set of built-in modules in its standard library for running server-side apps and allows for interaction with hardware directly.

It can let us manipulate files and do many things on a computer. It’s different from JavaScript in the browser since it does completely different things. One of the things Node.js can do is run a webserver to serve static and dynamic content.

In this article, we will get acquainted with Node.js by installing the Node.js run time platform and build simple web apps with it. We begin by downloading the Node.js run time.

To do this on Windows, we go to [https://nodejs.org/en/](https://nodejs.org/en/) and click the LTS link to download the Node.js run time and then double-click on the downloaded executable and follow the instructions. In Linux, we can use a package manager to download Node.js.

Each distribution will have a different way to download the Node.js run time. For example, in Ubuntu, we run the following commands to download Node.js:

```bash
$ sudo apt-get install curl  
$ curl -sL https://deb.nodesource.com/setup\_12.x | sudo -E bash -  
$ sudo apt-get install nodejs
```

When we run the commands above, we download the Node.js LTS version and install it. Then, we can run:

```bash
$ node -v
```

To check the version of Node.js that’s installed.

After Node.js run time is installed, we have to learn how to use the terminal.

On Windows, we will use the Node.js command prompt which is installed when we installed Node.js with the instructions above. The special command prompt has the Node.js environment already set up for us, while the regular command prompt does not.

Therefore, we need the Node.js command prompt to run Node.js apps. Windows 10 also has the Windows Subsystem for Linux, which provides us with different flavors of Linux as a command prompt program to let us do many things that can be done on Linux in Windows.

To install it, we have to go to the start menu and search for _Turn Windows Features on and off_, and then choose _Windows Subsystem for Linux_ and click _OK_. After that, restart your computer.

Then, after you’ve restarted, go to the Windows App Store and search for the Linux flavor that you want. The most common one is Ubuntu, so we can search for that and click _Install_.

After that, open the Ubuntu command prompt program that’s installed and let it run, then it will prompt you to create an account by setting a username and password for logging into the command prompt.

With the Windows Subsystem for Linux, the disk storage is shared with Windows, so we don’t have to worry about moving files around.

However, disk operations for version 1 of the Windows Subsystem for Linux are slow. Version 2 is much faster and will be out with the latest update of Windows 10.

For macOS and Linux users, they have terminal programs that let us run commands in the command prompt. It doesn’t need a special command prompt program to run Node.js apps. They both can run POSIX compliant programs.

An alternative for all users is to use a virtual machine for running Node.js on the operating system of your choice.

One popular choice is to use [VirtualBox](https://www.virtualbox.org/), which has support for many common operating systems like Windows and many flavors of Linux. It’s free and it’s supported by a big community.

Installing a new operating system on a VirtualBox virtual machine is easy and there are pre-made virtual machines available for download. For example, [https://www.osboxes.org/](https://www.osboxes.org/) has many Linux virtual machines made for VirtualBox.

Virtual machines use their own storage and share memory with the host machine, so virtual machines will take a significant chunk of memory that you set aside when you set up the virtual machine.

If you don’t like how virtual machines interact with your own keyboard, you can improve the experience by using a terminal program like PuTTY to connect to it.

However, you have to enable your virtual machine before doing this. For instance, to enable login from [PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/) to your VirtualBox virtual machine, we have to do the following steps:

*   Run `sudo apt install ssh` to install the SSH programs.
*   Turn off the virtual machine.
*   In VirtualBox, go to the _Settings_ menu, _Network_ section. On _Adapter 1_ choose _Host-only adapter_, then click _OK_.
*   Start your VirtualBox virtual machine, log in, and run `ifconfig` to get the IP address of your virtual machine.
*   Then, you can use that to log into the terminal program of your choice, like PuTTY.

After setting up Node.js on your virtual machine or computer, we can start writing Node.js programs. First, we have to use a text editor to write programs because we need a program that only saves plain text, which is what code is.

For example, in Windows, [Visual Studio Code](https://code.visualstudio.com/) is a great choice for writing JavaScript code. It has autocompletion for code and modules you’re trying to type in code to reference them.

Also, it’s fast and lightweight. It only takes 250MB of disk space and requires 1GB of memory and a 1.6 GHz processor.

These requirements are comparable to other text editors that are feature-rich. It also has settings for zoom, splitting the view of a single file, recognizes different types of files so that they can be highlighted properly for easy reading, and it has many add-ons to extend its functionality.

It also integrates with the command prompt or shell of your computer’s operating system so you can run commands directly in it.

JavaScript support is built-in, so we get syntax highlighting, autocomplete, and catching syntax errors automatically for JavaScript code. This is very helpful for increasing the productivity of programming with JavaScript since it helps reading and writing the code faster. It’s also built with JavaScript.

To make useful programs, we have to use other libraries to help us achieve this as we can’t write everything ourselves. Node.js has a standard library that lets us to many things like run a web server and manipulate files stored on the computer.

To do things that aren’t in the standard library, we can install Node.js packages and import or require them in your app’s code. Libraries are stored in package repositories and can be downloaded by a package manager.

For the Node.js ecosystem, the most popular package repository is the Node Package Manager or [npm](https://www.npmjs.com/). Npm is a repository for Node.js packages and we can download them with the `npm` program.

The npm program has many commands that let us download Node.js packages easily. The details of the packages you installed are stored in `package.json` in the project folder you’re in.

`package.json` can also store commands for scripts in the `scripts` section for `package.json`.

Also, to prevent package versions from changing and causing problems, a `package-lock.json` is created, indicating the version that’s installed when you install a package. If you use version control, you will check in both files so you get the right packages installed when you set up your app again.

Npm has many commands to do things to Node packages. The most common ones are below.

npm install
-----------

`npm install`, or `npm i` for short, is used to install packages.

If you don’t put a package name after `install`, it downloads all the packages listed in `package.json` if the dependencies aren’t installed yet or the version installed is outdated.

If you put a package name after `npm install`, it will install the package with that name as long as it finds the package. During the installation process, `npm` will run `npm run link` and `npm run build` to compile the packages.

You can install packages globally by running `npm install -g packageName`.

`npm prune`
-----------

`npm prune` removes unused packages. `npm run --production` is used to delete packages from the `devDependencies` section. The `--dry-run` option is used for checking which packages will be deleted before the actual run.

The `--json` option can be used to display results in JSON. With package-lock enabled, pruning is automatic.

`npm run`
---------

`npm run-script` lets you run custom scripts that you’ve written. `npm run` is an alias of this command.

`npm start`
-----------

`npm start` starts a package by running the command you define.

`npm update`
------------

`npm update` updates packages in the project. `npm update packageName` updates only the package with the name `packageName`. It will record the latest version to `package-lock.json`.

To install npm or upgrade npm to the latest version, run `npm install -g npm`.

* * *

Creating a Web Server
=====================

Now we have everything we need to write a basic web server. All it does it to serve the “Hello World” response by listening to the given port. We can view the message by going to the localhost with the given port.

What a web server does is, when given the URL that you put into the browser or an HTTP client, it gets the request you made, including URL, headers, cookies, and the request body, and then the server will do something in according to the request accepted.

The web server will get the request data like the URL, request method (GET, POST, PATCH, PUT, DELETE), headers, cookies, and the request body, and make the response according to the data in the request.

For example, if we go to http://localhost:9999/helloworld, then the webserver that listens to the port 9999 will get the request URL, and then if the URL is `helloworld`, which in this case it is, it will return the plain text response “Hello world”.

The response can have its own headers like file type and body data. It can be in different formats like plain text or JSON, which is plain text that has a format that looks like a JavaScript literal.

Also, the response will have a response code. The response code ranges from 100 to 500. Common ones include 200 for a generic success response, 201 for new data created, and 204 for responding with no content.

300 series responses are for redirect responses. 301 stands for moved permanently. 302 means resources are found. 400 series errors are for errors on the client-side.

For example, 400 is the generic bad request response for times when bad data is submitted to the server. 401 is for an unauthorized response when a user fails to log in with the correct credentials.

Typically, 403 is returned when a resource that’s not allowed to be accessed by the user is attempted to be accessed. 404 is a resource not found response.

405 is for making a request using an HTTP method that’s not authorized. 422 is another response that’s returned for sending bad data and can’t be processed by the server.

500 series errors are server-side errors. 500 is for generic server error. 502 is for a bad gateway, 503 indicates that service is unavailable, 504 is for gateway timeout.

Now we can write our web server with Node.js.

We will do it in two ways. We will use the `http` module that’s built into Node.js and the very popular [Express](https://expressjs.com/) web framework for building our web server app.

The one built with the `http` module looks like the following:

```javascript
const http = require("http");  
http  
  .createServer((request, response) => {  
    response.writeHead(200, { "Content-Type": "text/plain" });  
    response.write("Hello, World!");  
    response.end();  
  })  
  .listen(8888);  
console.log("Server listening on port 8888");
```

In the code above, we first import the `http` modules with the `const http = require(“http”);` line. Then, we used the `createServer` function to create the HTTP server.

Then, we pass in a callback function, which takes a `request` and `response` parameter. This is handy for processing data given the request that was taken in by the server. For this simple “Hello World” example, we just return the response.

We set the header with the `writeHead` function, available in the `response` object and set the response code, which is 200 for a successful response, and the `Content-Type` response header, which is set to `text/plain` since we want to return plain text.

Then, we run the `response.write` function with the `“Hello, World!”` string to display “Hello world” in the browser of the HTTP client of your choice. Calling `response.end()` will return the response to the browser of the HTTP client.

We can run the app by saving the code above in a file called `app.js` in the directory of your choice then running `node app.js` after going into the directory that you saved the file to.

The code above is OK for very simple apps like the Hello World app. However, when an app has more functionality, writing them using the `http` module would be a pain.

We would have to check the request and response in the listener, then we have checked the URLs that we want the users to go to and then manipulate the response and return it according to the things passed into the `request` object.

This is going to make creating complex apps difficult where there are lots of URLs that you want to check with different variations of headers and bodies in the request.

Therefore, we can use a framework to make this simpler. The Express framework is very simple and easy to use and lets us simplify our Hello World app.

To build our app with Express, we can create a folder, then go into the folder and run `npm init -y`.

This creates an empty `package.json` file that designates the folder as a Node.js project folder. Run `npm i express` to install the Express framework. Create `app.js` in the same folder and add:

```javascript
const express = require("express");
const app = express();
const port = 9999;
app.get("/", (req, res) => {
  res.send("Hello, World!");
});
app.listen(port, function() {
  console.log(`Server listening on port ${port}`);
});
```

We can run it by running `node app.js` in the folder you created and going to [http://localhost:9999,](http://localhost:9999,) where you would see the same thing as we have above.

It only displays “Hello World” when you go to http://localhost:9999. Other URLs like http://localhost:9999/abc won’t work as we only specified that the root URL, denoted by `“/”`, will return “Hello World!”

This is one thing that we don’t have in the webserver where we used the `http` module.

Node.js is a run time platform that has a great ecosystem. It adopted the V8 browser engine to interpret JavaScript code on the server.

It comes with its own set of built-in modules in its standard library for running server-side apps and allows for interaction with hardware directly.

It lets us manipulate files and do many things on a computer. It’s different from JavaScript in the browser since it does completely different things.

Creating a simple web server can be done simply with the `http` module built into the standard library of Node.js or we can use the Express framework for more advanced functionality.