7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
Advertisement
  1. Code
  2. Web Development

Learning Server-Side JavaScript With Node.js

Read Time: 10 mins

Node.js is a major framework for modern web development and makes it easy to create high-performance, real-time web applications. It allows JavaScript to be used end to end, both on the server and on the client. This tutorial will walk you through the installation of Node and show you how to write your first "Hello World" program. By the end, you'll go on to build a weather API with Node.js and Express.

What Is Node.js?

JavaScript has traditionally only run in the web browser, but after considerable interest in bringing it to the server side as well, Node.js was created.

Node.js is a bit different from other server technologies, because it is event-based rather than thread-based. Web servers like Apache that are used to serve PHP and other CGI scripts are thread-based because they spawn a system thread for every incoming request. While this is fine for many applications, the thread-based model does not scale well with many long-lived connections like you would need in order to serve real-time applications like instant messaging apps.

"Every I/O operation in Node.js is asynchronous..."

Node.js uses an event loop instead of threads, and is able to scale to millions of concurrent connections. It takes advantage of the fact that servers spend most of their time waiting for I/O operations, like reading a file from a hard drive, accessing an external web service or waiting for a file to finish being uploaded, because these operations are much slower than in-memory operations. Every I/O operation in Node.js is asynchronous, meaning that the server can continue to process incoming requests while the I/O operation is taking place. JavaScript is extremely well suited to event-based programming because it has anonymous functions and closures which make defining inline callbacks a cinch, and JavaScript developers already know how to program in this way. This event-based model makes Node.js very fast, and makes scaling real-time applications very easy.

1. Installation

Node.js is officially supported on Linux, macOS, Microsoft Windows, SmartOS, and FreeBSD. To install a recent version of Node.js on Windows (v16 and upwards), your computer must be running on Windows 8.1, 10, or 11.

Node.js comes built-in with its own package manager called the node package manager, or npm for short, which allows you to install 3rd-party modules from the npm registry.

  1. Download the latest release of Node.js from nodejs.org (the latest version at the time of this writing is 17.9.0 and the latest LTS version is 16.14.2). This should download the .msi file on your computer.
  2. Run the file and go over the setup wizard. Most options are optional—you don't need to change the program path unless you have a good reason to. You can choose to install Chocolatey (a windows package manager) or skip the step.
  3. Once the wizard is completed and Node has been installed successfully, open the terminal, and run node -v to see the installed Node version. Run npm -v to see the npm version.
 
Also, if you search Node in your programs, you should find the Node.js command prompt.
 

The command prompt provides a REPL (Read-Eval-Print Loop) where you can type in JavaScript Node.js code and have the code immediately evaluated and the results outputted. You can also load JavaScript from an external file into the REPL session etc.

2. Hello World!

Learning any new technology begins with a "Hello World!" tutorial, so we will create a simple HTTP server that serves up that message.

First, we'll create a fresh Node.js project. To create one, open your terminal, change to the directory that you want your project in and run the following command:

You'll be prompted to provide some information about your library including the library name, author, entry file, licence, and version, and when done, a package.json file will be created using the information provided. To skip this step, attach the -y flag to the above command and Node.js will generate a package.json file with some default values.

Then, create an empty JavaScript file and name it test.js.

For the next step, you have to understand the Node.js module system. In Node, functionality is encapsulated in modules which must be loaded in order to be used. There are many modules listed in the Node.js documentation. You load these modules by using the require function like so (inside test.js):

This loads the util module, which contains utility functions for dealing with system-level tasks like printing output to the terminal. To use a function in a module, you call it on the variable in which you stored the module—in our case util.

To run this script, just run the node command with the filename of the JavaScript file as an argument.

This will output "Hello World!" to the command line when run.

To create an HTTP server, you must require the http module.

This script imports the util and http modules, and creates an HTTP server. The anonymous function that is passed into http.createServer will be called whenever a request comes in to the server. Once the server is created, it is told to listen on port 8080.

When a request to the server comes in, we first send HTTP headers with the content type and status code of 200 (successful). Then we send "Hello World!" and close the connection. You might notice that we have to explicitly close the connection. This will make it very easy to stream data to the client without closing the connection.

If you run this script and go to http://localhost:8080/ in your browser, you will see Hello World!.

hello world serverhello world serverhello world server

3. A Simple Static File Server

OK, so we have built an HTTP server, but it doesn't send anything except for "Hello World," no matter what URL you go to. Any HTTP server must be able to send static files such as HTML files, images, and other files. The following code does just that:

We start by requiring all of the modules that we will need in our code. This includes the sys, http, url, path, and fs or filesystem modules.

Next we create an HTTP server as we did before. This time, we will use the url module to parse the incoming URL of the request and find the pathname of the file being accessed. We find the actual filename on the server's hard drive by using path.join, which joins process.cwd(), or the current working directory, with the path to the file being requested.

Next, we check if the file exists, which is an asynchronous operation and thus requires a callback. If the file does not exist, a 404 Not Found message is sent to the user and the function returns. Otherwise, we read the file using the fs module using the "binary" encoding, and send the file to the user. If there is an error reading the file, we present the error message to the user, and close the connection. Because all of this is asynchronous, the server is able to serve other requests while reading the file from the disk, no matter how large it is.

If you run this example and navigate to http://localhost:8080/path/to/file, that file will be shown in your browser.

static_site_imagestatic_site_imagestatic_site_image
Static Site

4. Build a Weather API in Node.js With Express

Building on our static file server, we will build a server in Node.js that fetches and shows the expected weather condition of a given city. To start, we will need two extra third-party modules in this example: the express module and the axios module. Express is a web framework used to build RESTful APIs in Node.js applications. We'll be using the Express module to build a single API endpoint that will take the city from each request and respond with an HTML body containing the forecasted weather condition for the city. The weather information will come from an external API—so we'll use the axios client to make an API request.

First we'll install both the Express and axios modules at the same time using the following command:

This will install both modules from the npm registry. The dependencies field will be added to the JSON object inside your package.json, and you should see the installed version of each dependency. The node_modules folder will also be generated to track all the modules that Express and axios use.

Now that we have installed Express, we'll be creating our Express app inside test.js.

Here, we first import Express and axios. Then we set up a GET route on the index path '/', responding with a simple string. Finally, we serve the Express application on localhost:3000.

result_imageresult_imageresult_image
Output

Go to Open Weather API and subscribe to Current weather and forecasts collection for free to get your API key (you'll be prompted to sign up and get your key from the API Key section).

With your API key secured, it's time to build the code that will fetch and return the forecasted weather condition for a provided location in our GET route.

At the start of the test.js file, below the imports, copy your API key from Open Weather API and store the value to a variable.

Now, replace your app.get() code with the following:

The first thing we do is retrieve the query string (city) from the query property.

Then we make a GET request to the weather forecast API using axios. The URL will need two variables: the city we want to get a forecast for and the unique API key provided in your Open Weather API dashboard.

We set up a then function to handle the response—if the response status is 200 (meaning OK), we send back the weather description for the city, provided in the returned data. We send this back to the browser as a response using the res.send() method. On error, we simply log the error data to the console via catch.

Save your test.js file, run node test.js on your command line, and type the following URL in your browser:

Note that nairobi can be replaced with any city of your choice. Here are the results you should get.

forcast_imageforcast_imageforcast_image
Weather Forecast for Nairobi

Next Steps

Node.js is a very exciting technology that makes it easy to create high-performance real-time applications. I hope you can see its benefits and can use it in some of your own applications. Because of Node's great module system, it is easy to use open-source third-party libraries in your application, and there are modules available for just about everything: including database connection layers, templating engines, mail clients, and even entire frameworks connecting all of these things together.

Happy noding!

This post has been updated with contributions from Kingsley Ubah. Kingsley is passionate about creating content that educates and inspires readers. Hobbies include reading, football and cycling.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Scroll to top
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.