What is Nodejs

Nodejs is a cross platform server side JavaScript runtime giving us the ability to run JavaScript in a server environment. This is counter to what JavaScript was initially used for which is front end, client side development. One of the best things that Nodejs provides us is its asynchronous behavior. Instead of blocking (read more about blocking vs. nonblocking here) the main thread with the event loop or function calls, Nodejs handles everything asynchronously. No blocking means fewer hang ups and less worry!

What this asynchronous behavior means for us is that we can handle efficiently more connections. An example of this is a request for some file on the server. Using PHP, ASP, or another blocking type language, if we want the contents of a file the process looks like this

  1. Request is received.
  2. Sends the task to the computer’s file system.
  3. Waits while the file system opens and reads the file.
  4. Returns the content to the client.
  5. Ready to handle the next request.

When we use Nodejs however, the process looks like this

  1. Request is received.
  2. Sends the task to the computer’s file system.
  3. Ready to handle the next request.
  4. When the file system has opened and read the file, the server returns the content to the client.

As you can see, with Nodejs there is no blocking behavior in waiting for the file system or the OS in general. Nodejs sends off the request to the file system and then readies itself for another request. In the meantime it is asynchronously waiting for the file system to complete the open and read. This is the beauty of asynchronous behavior.

Now, let’s make an app with Nodejs!

How to Install Nodejs

We can’t make an app if we don’t have it installed, so let’s start there. Find your system below.

Linux

One of the simplest installs of Nodejs is with linux. Using your flavor’s package manager (here I’m using apt), install nodejs with the following command

$ sudo apt install nodejs

Let that install and you should be good to go! To check if it properly installed, check your version using

$ node --version

Mac

With a Mac, it’s easiest to use brew to install Nodejs with the following

$ brew install node

If you don’t have homebrew installed, you can head over here to download it. If you must install Nodejs another way then you can head over to their website and download the installer.

Once installed, check to make sure by seeing what version you have installed

$ node --version

Windows

If you’re on windows you can head over to their website and download the installer there. After going through the installation, you should be able to use node within powershell. For more details on the installation process, check out this article.

Once installed, check to make sure by seeing what version you have installed

$ node --version

Creating a Nodejs Project

Starting the Nodejs project

In this example, we are going to create a very simple project that returns a simple webpage.

When you install Nodejs, along with it comes the node package manager (npm). If you’re coming from Python, this is like pip. First what we’ll do is create a directory

$ mkdir simple-node-server
$ cd simple-node-server

Next we’ll use npm to start our project. This will create a package.json file which will store information like author, project name, and dependencies.

$ npm init

When you execute the init command, you will be taken through a set of questions including

  • package name – default value will be your folder name
  • version – default value will be 1.0.0 which you can keep or change to what versioning system you use
  • description – fill with the description of your project
  • entry point – I like to change this to server.js, but the default is index.js
  • test command – leave blank for now, this will be run with npm test
  • git repository – set this to your remote URL if you have one, otherwise leave blank
  • keywords – keep empty for now
  • author – put your name
  • license – default will be ISC, keep or change to another license as you see fit

Finally, you will be given a final review of how your package.json file will look. Hit enter to confirm and we’re set to continue.

Install Express

The easiest and quickest way to get a server up and going in Nodejs is by using the Express framework. Express provides a large array of different http features for us to use. In fact, many other frameworks are built on Express!

It’s very simple to install Express. Simple use this command in your project directory

$ npm install  --save express

This will install express into our project directory and save it as a dependency in our package.json.

Create an Index Page

For our simple project, we are going to create a simple hello world html page for our server to send. Pop open your favorite text editor (if yours is VS Code, check out my compilation of the best VS Code extensions for full stack developers here) and create an index file. Add the following to your index.html file

<DOCTYPE html>
<html>
  <body>
    <p>Hello World</p>
  </body>
</html>

There we go, nice and simple. To deliver this file we’re going to need to create the server.

Create a Nodejs Server

Remember what name you called your entry point? The default was index.js but I rename mine to server.js. Create a file with that same name. Then we’re going to add the following to it

const express = require('express');
const app = express();

app.get('/', (req, res) => {
 cres.sendFile("index.html", {root: __dirname});
})

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000/");
});

Let’s take a closer look at this. First, we import express and create our app

const express = require('express');
const app = express();

Next, we add an HTTP GET route to our app. This route is for the path “/” or whatever the host/domain name is with nothing else attached. The home page you might say.

app.get('/', (req, res) => {

The get method takes two arguments, the path and a callback function. In this case we are passing in an anonymous function. The callback function should take two arguments, the request and a response.

In our callback is where we do our manipulations, calls, or any other general operations that we want to happen when a user requests the path. In our case, we want to return our index file to the user. We do this by using our response object, res. This object has a method called sendFile which takes the path of the file and options object. In our case, we want to use “index.html” and create an options object with what our root is. This is because we are specifying a relative path and not an absolute path. For the root path, we can use a Nodejs variable called __dirname which will be the path of the parent directory where our script is located.

  res.sendFile("index.html", {root: __dirname});

Finally, we tell our app that we want to listen on port 3000 of localhost. Our express app has a method called listen that we can use. listen takes a few arguments including port and a callback. It can also take a hostname and a backlog, but for now we are just going to be using the port and callback and Express will default to using localhost as the hostname. In our case the callback function will be a simple console.log to let us know we are up and running with no problems.

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000/");
});

That’s it!

All the files are in place and we’re ready to run our server. Head over to your terminal/command line and run the following (replace server.js with whatever you called your file)

$ node server.js

After a second you should see it print out

Server running at http://localhost:3000/

Now you can navigate to that address in your browser of choice and see your beautiful Hello World index file served to you.

It’s as simple as that to get started with server development with Nodejs. This is a very, very simple example but the basis for most Nodejs servers. There’s quite a bit on top of this but this is a solid starting point for you to learn more about server development with Nodejs. If you’re ready, then checkout Web Development with Node and Express: Leveraging the JavaScript Stack to take the next step in learning about Nodejs and Express!

Stay up to date on my recent posts
Get the latest content first.
We respect your privacy.