Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Node.js Tutorial for Beginners (Part 1): Intro to Node and Express

DZone 's Guide to

Node.js Tutorial for Beginners (Part 1): Intro to Node and Express

In the first post of this series, we examine how to get started with Node.js and how to use Express to create a few basic web pages.

· Web Dev Zone ·
Free Resource

Over the course of the past year and a half, I've been slowly, and a bit sporadically, teaching myself web development technologies. I've had some success with HTML, CSS, and basic, vanilla JavaScript (you can see some of my Fiddles here). But now I'm interested in diving into Node.js, and I'm using this series to chronicle my journey. Hopefully, I'm not in over my head, but, even if I am, I hope this will help fellow novices or experienced devs new to Node and JavaScript. 

Node.js is a fascinating technology with a quickly growing user base. Though it's often referred to as a framework, Node actually functions as a JavaScript runtime, powered by Google's V8 engine — the same engine used to power the Chrome browser. Thus, Node essentially takes the place of the browser in the execution of JavaScript code. This allows developers to use JavaScript, a language designed to be compiled and run on the client-side, on the server-side, making a full-stack JavaScript application possible. In addition to that, Node is a pretty scalable solution, as proven by its adoption by several large-scale organizations, including Netflix, Uber, PayPal, and NASA. 

Introduction

To begin, let's go ahead and download Node.js onto our machines. You can find and download Node from their official website (nodejs.org). Once on the homepage, select the version you'd prefer to use. In the screenshot below, the left-hand option (8.12.0) is the latest stable release. 

Node.js download

Your computer will take you through a few prompted pop-up windows, and then you should be good to go with Node.js. You can then open your terminal (whichever one comes on your machine) and get started with the commands we'll be going over. Also, I'll be using the Atom code editor, but feel free to use whichever one suits you best (VS Code, SublimeText, etc.).

Project Idea

I'll be basing the app I work on in this series off of a project from a Udemy course (found here) that I've been using on-and-off for a while. I love to travel, and the US National Parks are some of my favorite places to go. To teach myself topics like Node.js, Express.js, templating engines, and Bootstrap, I'm going to design an application to keep track of my park travels. In Part 1 of this series, we're going to get some servers up and running with Node and Express.  

Getting Acquainted With Node

The whole point of Node is to create an environment in which one can work with JavaScript on the backend. To that end, before getting started with creating web pages, I'd like to take a moment to explore how to work with Node in the console. To do so, let's work on setting up the server we'll use to run our future app.  

Creating a server without the aid of any packages can be a bit convoluted. According to the Mozilla Developer Network, we can use the following code to set up this server: 

//Load HTTP module
const http = require("http");
const hostname = '127.0.0.1';
const port = 3000;

//Create HTTP server and listen on port 3000 for requests
const server = http.createServer((req, res) => {

  //Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

//listen for request on port 3000, and as a callback function have the port listened on logged
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

As someone new to the subject, all these constants and functions made my head spin. In the next section, I'll go over how using the Express package for Node.js makes this whole process much simpler.  

Setting Up Express

One of the best, and most ubiquitous, packages for Node is Express.js, and that's what we'll be looking at for the remainder of this article. 

The Express docs can be found on npm's official website, here, or Express's official website. Per the npm docs, some of the advantages of using Express are: 

  • Robust routing.

  • HTTP helpers (redirection, caching, etc.).

  • A views system for supporting 14+ template engines.

All-in-all, it's a powerful package, good for beginners like me and seasoned developers looking to dive into Node. 

First thing's first, we need to create the directory in which we'll be working. That's a simple $mkdir command followed by the name of the directory we wish to create (I've called this file dzone_app1). Next, we need to cd into our newly created directory and use the $touch command to create the application that will hold our server logic; I've titled mine index.js, though I have seen tutorials that delineate this from other files with the name server.js.  

Getting Express installed is easy. In your terminal, type the command: npm intsall express --save. One of the great things about Node is that it comes hooked up to the official node package manager (npm for short) repository of packages. Meaning, in the command we just used, npm is telling Node to draw from this repository and to installthe express package. The --save bit of the command will save Express in this application so we don't have to worry about reinstalling it later on. 

Okay, now we can actually get to some coding. In the index.js file, let's use the following code to tell the application we're using Express:

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

While one can use the var variable declarator for this as well, current documentation indicates const is best practice. 

To get the server up and running, we need to use the following code in our index.js file: 

//create a server on a local host like this: 
app.listen(port, function (){
  console.log("Server running");
});

To this point, the code required to get a server running, and that prints a message to the console, looks like this: 

const express  = require("express");
const app = express(); 
const port = 3000;

app.listen(port, function (){
  console.log("Server running");
});

6 lines of code; way simpler than the way we set up a server in the previous section. 

Making Things Happen

Alright, now let's make something happen on a page! Let's head back into the index.js file and type in the following code:

app.get("/", function(req,res){
   res.send("Hello World!"); 
});

Restart the server and go to its landing page. Once it's loaded, we'll see the message, "Hello World!"

Image title

Sweet, it works! But, just to make sure we've got it down, let's try to create another page at the address, /parks. Head back into the index.js file and add in the following code: 

app.get("/parks", function(req,res){
    res.send("The Parks You've Seen");
});

Woo! After restarting the server and navigating to the /parks page, we should see the message, "The Parks You've Seen," in tiny print on the webpage. 

Image title

Altogether, the code thus far looks like this: 

const express  = require("express");
const app = express(); 
const port = 3000;

app.get("/", function(req,res){
   res.send("Hello World!"); 

});

app.get("/parks", function(req,res){
    res.send("The Parks You've Seen");
});

app.listen(port, function (){
  console.log("Server running");
});

Conclusion

That's all the brainpower I've got for today. In the next article, we'll tackle setting up a templating engine so we can actually make decent-ish looking pages.

'Til then, cheers! 

Topics:
web dev ,node.js tutorial for beginners ,express.js tutorial ,web application development ,backend development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}