Loading
computer with code

An Introduction to Node.js: Server Side JavaScript

By Anthony Li

November 11, 2020

This post is significantly code-heavy. Familiarity with a text editor, JavaScript, and the command line is assumed for this post.

In this post, we’ll take you through a brief beginner’s guide to Node.js. We’ll learn what it is, we’ll install it, and we’ll use it to start our first web server.

You may have heard of JavaScript; it’s the main programming language for the web, and it’s responsible for all the interactivity on websites today.

But normal JavaScript is quite limited:

  • It’s confined to the web browser.

  • It can’t read or write files outside of the browser.

  • It can only make a limited set of network connections to the Internet.

  • It can’t freely communicate with devices and databases on the computer.

  • Worst of all, typical JavaScript runs on the client side, so all your business logic will be visible to your users.

Node.js solves this problem by running JavaScript on the server side, without a web browser. It can perform a variety of tasks, such as running web servers, querying databases, and more. It uses V8, the same JavaScript execution engine used by Google Chrome.

Installation

We’ll get started with the most exciting part of any software development project: installing things.

Begin by downloading the Node.js installer at https://nodejs.org/en/. Open the installer, and follow the instructions to install.

If you’re using Linux or are looking for something more advanced, consider installing from a package manager.

Hello, World!

Like most other tutorials, we’ll get started with Node.js with a basic “Hello, world!” program.

Open up a terminal (Command Prompt on Windows or Terminal on macOS), and run this command to start a Node.js REPL:

     node

 

Be sure to press the enter/return key after typing node.

If everything went well, you should see this:

     Welcome to Node.js (version).

     Type ".help" for more information.

     >

 

Here we can type JavaScript code and see the results in real-time. Our “Hello, World!” program will consist of a single line:

     console.log("Hello, world!")

 

We should get back:

     > console.log("Hello, world!") 

     Hello, world!

     undefined

 

Note how console.log is the same function used in the browser; that is, opening Inspect Element and running console.log("Hello, world!") in the JavaScript console should yield the same thing.

Congratulations, you’ve just written your first Node.js program!

Feel free to explore what Node.js can do - nearly everything in JavaScript will work in Node.js. If you want to learn more advanced JavaScript, use Codecademy or try out the W3Schools tutorial.

Programs as Files

Let’s take our basic “Hello, World!” program and write it in a file. Open a new text file in your preferred text/code editor and save it with the name and extension helloworld.js in your Documents or My Documents folder.

In it, type:

     console.log("Hello, world!")

 

Open up a terminal and type:

     cd Documents

 

(If you’re using OneDrive to store your Documents folder, type OneDrive/Documents instead of Documents.)

Then, type:

     node helloworld.js

 

This should print out “Hello, World!”, just like before.

Using npm

Node.js is great on its own, but where it really shines is through a tool called npm.

npm is Node.js’s package manager - it lets you install libraries, or pieces of code created by others, to use in your code. There are libraries on npm for nearly everything - running web servers, querying databases, even ordering pizza.

Let’s create a new project with npm. Create a new folder in your Documents folder named mygreatwebapp. Then, open up a terminal, and if you haven’t done so, cd into your Documents folder. Finally, run:

cd mygreatwebapp

npm init

 

You’ll be asked several questions about your project. Stick with the defaults by mashing the enter key, or override them with your own values.

This tool will create a new file in your folder, package.json. This stores all the metadata regarding your “package,” such as its name, its author, its licensing details, and most importantly, the libraries and dependencies it uses.

Using express

We’ll use npm to install our first dependency. express. Express is a framework used to create web apps, and it’s one of the most popular libraries on the npm registry. To install it, run this in your terminal:

     npm install --save express

 

This command installs the Express library, while the --save parameter adds it to your package.json file.

Let’s get started by creating a quick web app. Make a new file called index.js. Begin by writing this line:

     const Express = require("express")

 

This fetches the express library and stores it in a constant called Express.

Now, we’ll use this to construct a new web app:

     const app = new Express()

 

And we’ll tell the app to listen to port 12345:

     app.listen(12345)

 

Save the file and run it using Node.js. Browse to http://localhost:12345, and if you see “Cannot get /“, everything is working.

(If you get a prompt from Windows Firewall, ensure you allow access to run the web server.)

Adding Your First Route

Let’s have the web server do something useful. We’ll set it up so that it displays Hello, world! when we browse to it.

To do so, paste in these lines before the call to app.listen:

     app.get("/", function (req, res) {

         res.send("Hello, world!");

     })

 

This tells Express that when someone requests the main page, it should send “Hello, world!” to the browser.

Back in the terminal, press Control-C to stop Node.js if it’s running, and type node index.js instead. Browse to http://localhost:12345 and see if it displays “Hello, world!”

Congratulations! In a few steps, you’ve set up a fully working web server with Node.js!

Further Reading

You can do tons more with Node.js, npm, Express, and JavaScript in general. If you’d like to continue further and want something hands-on, try Codecademy’s Express tutorial or browse the Express documentation for examples.

If you have any questions or are confused, feel free to contact me at me@anli.dev.