Expert Node.js Support
Learn more

Getting Started

Node Hero - Your First Node.js HTTP Server

This is the 4th post of the tutorial series called Node Hero - in these chapters you can learn how to get started with Node.js and deliver software products using it.

In this chapter, I’ll show how you can fire up a simple Node.js HTTP server and start serving requests.

The http module for your Node.js server

When you start building HTTP-based applications in Node.js, the built-in http/https modules are the ones you will interact with.

Now, let's create your first Node.js HTTP server! We'll need to require the http module and bind our server to the port 3000 to listen on.

// content of index.js
const http = require('http')  
const port = 3000

const requestHandler = (request, response) => {  
  console.log(request.url)
  response.end('Hello Node.js Server!')
}

const server = http.createServer(requestHandler)

server.listen(port, (err) => {  
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

You can start it with:

$ node index.js

Things to notice here:

  • requestHandler: this function will be invoked every time a request hits the server. If you visit localhost:3000 from your browser, two log messages will appear: one for / and one for favicon.ico
  • if (err): error handling - if the port is already taken, or for any other reason our server cannot start, we get notified here

The http module is very low-level - creating a complex web application using the snippet above is very time-consuming. This is the reason why we usually pick a framework to work with for our projects. There are a lot you can pick from, but these are the most popular ones:

For this and the next chapters we are going to use Express, as you will find the most modules on NPM for Express.

Node.js Monitoring and Debugging from the Experts of RisingStack

Build performant applications using Trace
Learn more

Express

Fast, unopinionated, minimalist web framework for Node.js - http://expressjs.com/

Adding Express to your project is only an NPM install away:

$ npm install express --save

Once you have Express installed, let's see how you can create a similar application as before:

const express = require('express')  
const app = express()  
const port = 3000

app.get('/', (request, response) => {  
  response.send('Hello from Express!')
})

app.listen(port, (err) => {  
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

The biggest difference what you have to notice here is that Express by default gives you a router. You don't have to check manually for the URL to decide what to do, but instead, you define the application's routing with app.get, app.post, app.put, etc. They are translated to the corresponding HTTP verbs.

One of the most powerful concepts that Express implements is the middleware pattern.

Middlewares

You can think of middlewares as Unix pipelines, but for HTTP requests.

Express middlewares for building a Node.js HTTP server

In the diagram you can see how a request can go through an Express application. It travels to three middlewares. Each can modify it, then based on the business logic either the third middleware can send back a response or it can be a route handler.

In practice, you can do it this way:

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

app.use((request, response, next) => {  
  console.log(request.headers)
  next()
})

app.use((request, response, next) => {  
  request.chance = Math.random()
  next()
})

app.get('/', (request, response) => {  
  response.json({
    chance: request.chance
  })
})

app.listen(3000)  

Things to notice here:

  • app.use: this is how you can define middlewares - it takes a function with three parameters, the first being the request, the second the response and the third one is the next callback. Calling next signals Express that it can jump to the next middleware or route handler.
  • The first middleware just logs the headers and instantly calls the next one.
  • The seconds one adds an extra property to it - this is one of the most powerful features of the middleware pattern. Your middlewares can append extra data to the request object that downstream middlewares can read/alter.

Error handling

As in all frameworks, getting the error handling right is crucial. In Express you have to create a special middleware function to do so - a middleware with four parameters:

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

app.get('/', (request, response) => {  
  throw new Error('oops')
})

app.use((err, request, response, next) => {  
  // log the error, for now just console.log
  console.log(err)
  response.status(500).send('Something broke!')
})

Things to notice here:

  • The error handler function should be the last function added with app.use.
  • The error handler has a next callback - it can be used to chain multiple error handlers.

Rendering HTML

So far we have taken a look on how to send JSON responses - it is time to learn how to render HTML the easy way. For that, we are going to use the handlebars package with the express-handlebars wrapper.

First, let's create the following directory structure:

├── index.js
└── views
    ├── home.hbs
    └── layouts
        └── main.hbs

Once you have that, populate index.js with the following snippet:

// index.js
const path = require('path')  
const express = require('express')  
const exphbs = require('express-handlebars')

const app = express()

app.engine('.hbs', exphbs({  
  defaultLayout: 'main',
  extname: '.hbs',
  layoutsDir: path.join(__dirname, 'views/layouts')
}))
app.set('view engine', '.hbs')  
app.set('views', path.join(__dirname, 'views'))  

The code above initializes the handlebars engine and sets the layouts directory to views/layouts. This is the directory where your layouts will be stored.

Once you have this setup, you can put your initial html into the main.hbs - to keep things simple let's go with this one:

<html>  
  <head>
    <title>Express handlebars</title>
  </head>
  <body>
    {{{body}}}
  </body>
</html>  

You can notice the {{{body}}} placeholder - this is where your content will be placed - let's create the home.hbs!

<h2>Hello {{name}}<h2>  

The last thing we have to do to make it work is to add a route handler to our Express application:

app.get('/', (request, response) => {  
  response.render('home', {
    name: 'John'
  })
})

The render method takes two parameters:

  • The first one is the name of the view,
  • and the second is the data you want to render.

Once you call that endpoint you will end up with something like this:

<html>  
  <head>
    <title>Express handlebars</title>
  </head>
  <body>
    <h2>Hello John<h2>
  </body>
</html>  

This is just the tip of the iceberg - to learn how to add more layouts and even partials, please refer to the official express-handlebars documentation.

Debugging Express

In some cases, you may need to see what happens with Express when your application is running. To do so, you can pass the following environment variable to Express: DEBUG=express*.

You have to start your Node.js HTTP server using:

$ DEBUG=express* node index.js

Download the whole Node Hero series as a single pdf

Summary

This is how can you set up your first Node.js HTTP server from scratch. I recommend Express to begin with, then feel free to experiment. Let me know how did it go in the comments.

In the next chapter, you will learn how to retrieve information from databases - subscribe to our newsletter for updates.

In the meantime if you have any questions, don't hesitate to ask!

Node Hero - Using NPM: Tutorial

Node Hero - Using NPM: Tutorial

This is the second post of the tutorial series called Node Hero - in these chapters you can learn how to get started with Node.js and deliver software products using it. In this chapter, you'll learn what NPM is and how to use it. Let's get started!

NPM in a Nutshell

NPM is the package manager used by Node.js applications - you can find a ton of modules here, so you don't have to reinvent the wheel. It is like Maven for Java or Composer for PHP. There are two primary interfaces you will interact with - the NPM website and the NPM command line toolkit.

Both the website and the CLI uses the same registry to show modules and search for them.

The Website

The NPM website can be found at https://npmjs.com. Here you can sign up as a new user or search for packages.

npm website for Node Hero using npm tutorial

The Command Line Interface

To run the CLI you can run it simply with:

npm  

Note, that NPM is bundled with the Node.js binary, so you don't have to install it - however, if you want to use a specific npm version, you can update it. If you want to install npm version 3, you can do that with: npm install [email protected] -g.

Node.js Monitoring and Debugging from the Experts of RisingStack

Build performant applications using Trace
Learn more

Using NPM: Tutorial

You have already met NPM in the last article on Getting started with Node.js when you created the package.json file. Let's extend that knowledge!

Adding Dependencies

In this section you are going to learn how to add runtime dependencies to your application.

Once you have your package.json file you can add dependencies to your application. Let's add one! Try the following:

npm install lodash --save  

With this single command we achieved two things: first of all, lodash is downloaded and placed into the node_modules folder. This is the folder where all your external dependencies will be put. Usually, you don't want to add this folder to your source control, so if you are using git make sure to add it to the .gitignore file.

This can be a good starting point for your .gitignore

Let's take a look at what happened in the package.json file! A new property called dependencies have appeared:

"dependencies": {
  "lodash": "4.6.1"
}

This means that lodash with version 4.6.1 is now installed and ready to be used. Note, that NPM follows SemVer to version packages.

Given a version number MAJOR.MINOR.PATCH, increment the MAJOR version when you make incompatible API changes, MINOR version when you add functionality in a backwards-compatible manner, and PATCH version when you make backwards-compatible bug fixes. For more information: http://semver.org/

As lodash is ready to be used, let's see how we can do so! You can do it in the same way you did it with your own module except now you don't have to define the path, only the name of the module:

// index.js
const _ = require('lodash')

_.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 });  
// → { 'a': 1, 'b': 2, 'c': 3 }

Adding Development Dependencies

In this section you are going to learn how to add build-time dependencies to your application.

When you are building web applications, you may need to minify your JavaScript files, concatenating CSS files and so on. The modules that will do it will be only ran during the building of the assets, so the running application doesn't need them.

You can install such scripts with:

npm install mocha --save-dev  

Once you do that, a new section will appear in your package.json file called devDependencies. All the modules you install with --save-dev will be placed there - also, they will be put in the very same node_modules directory.

NPM Scripts

NPM script is a very powerful concept - with the help of them you can build small utilities or even compose complex build systems.

The most common ones are the start and the test scripts. With the start you can define how one should start your application, while test is for running tests. In your package.json they can look something like this:

  "scripts": {
    "start": "node index.js",
    "test": "mocha test",
    "your-custom-script": "echo npm"
  }

Things to notice here:

  • start: pretty straightforward, it just describes the starting point of your application, it can be invoked with npm start
  • test: the purpose of this one is to run your tests - one gotcha here is that in this case mocha doesn't need to be installed globally, as npm will look for it in the node_modules/.bin folder, and mocha will be placed there as well. It can be invoked with: npm test.
  • your-custom-script: anything that you want, you can pick any name. It can be invoked with npm run your-custom-script - don't forget the run part!

Scoped / Private Packages

Originally NPM had a global shared namespace for module names - with more than 250.000 modules in the registry most of the simple names are already taken. Also, the global namespace contains public modules only.

NPM addressed this problem with the introduction of scoped packages. Scoped packages has the following naming pattern:

@myorg/mypackage

You can install scoped packages the same way as you did before:

npm install @myorg/mypackage --save-dev  

It will show up in your package.json in the following way:

"dependencies": {
  "@myorg/mypackage": "^1.0.0"
}

Requiring scoped packages works as expected:

require([email protected]/mypackage')  

For more information refer to the NPM scoped module docs.

Download the whole Node Hero series as a single pdf

Next Up: Async Programming

In the next chapter, you can learn the principles of async programming using callbacks and Promises - subscribe to our newsletter for updates.

In the meantime if you have any questions, don't hesitate to ask!

Node Hero - Getting Started With Node.js Tutorial

Node Hero - Getting Started With Node.js Tutorial

This is the first post of an upcoming Node.js tutorial series called Node Hero - in these chapters, you can learn how to get started with Node.js and deliver software products using it.

Update: as a sequel to Node Hero, we have started a new series called Node.js at Scale. Check it out if you are interested in more in-depth articles!

We are going to start with the basics - no prior Node.js knowledge is needed. The goal of this series is to get you started with Node.js and make sure you understand how to write an application using it, so don't hesitate to ask us if anything is unclear!

In this very first tutorial, you will learn what Node.js is, how to install it on your computer and how to get started with it - so in the next ones we can do actual development. Let's get started!

Node.js in a Nutshell

node.js logo in node hero getting started tutorial The official Node.js logo

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

In other words: Node.js offers you the possibility to write servers using JavaScript with an incredible performance. As the official statement says: Node.js is a runtime that uses the same V8 Javascript engine you can find in the Google Chrome browser. But that wouldn't be enough for Node.js's success - Node.js utilizes libuv, a multi-platform support library with a focus on asynchronous I/O.

libuv logo in node hero getting started tutorial The official libuv logo

From a developer's point of view Node.js is single-threaded - but under the hood libuv handles threading, file system events, implements the event loop, features thread pooling and so on. In most cases you won't interact with it directly.

Node.js Monitoring and Debugging from the Experts of RisingStack

Build performant applications using Trace
Learn more

Installing Node.js to get started

To get the latest Node.js binary you can visit the official Node.js website: https://nodejs.org/en/download/.

With this approach it is quite easy to get started - however if later down the road you want to add more Node.js versions, it is better to start using nvm, the Node Version Manager.

Once you install it, you can use a very simple CLI API that you can interact with:

Installing Node.js Versions

nvm install 4.4  

Then, if you want to check out the experimental version:

nvm install 5  

To verify that you have Node.js up and running, run this:

node --version  

If everything is ok, it will return the version number of the currently active Node.js binary.

Using Node.js Versions

If you are working on a project supporting Node.js v4, you can start using it with the following command:

nvm use 4  

Then you can switch to Node.js v5 with the very same command:

nvm use 5  

Okay, now we know how to install and switch between Node.js versions - but what's the point?

Since the Node.js Foundation was formed, Node.js has a release plan. It's quite similar to the other projects of the Linux Foundation. This means that there are two releases: the stable release and the experimental one. In Node.js the stable versions with long-term support (LTS) are the ones starting with even numbers (4, 6, 8 ...) and the experimental version are the odd numbers (5, 7 ...). We recommend you to use the LTS version in production and try out new things with the experimental one.

If you are on Windows, there is an alternative for nvm: nvm-windows.

Node.js tutorial: Hello World

To get started with Node.js, let's try it in the terminal! Start Node.js by simply typing node:

$ node
>

Okay, let's try printing something:

$ node
> console.log('hello from Node.js')

Once you hit Enter, you will get something like this:

> console.log('hello from Node.js')
hello from Node.js  
undefined  

Feel free to play with Node.js by using this interface - I usually try out small snippets here if I don't want to put them into a file.


It is time to create our Hello Node.js application!

Let’s start with creating a file called index.js. Open up your IDE (Atom, Sublime, Code - you name it), create a new file and save it with the name index.js. If you’re done with that, copy the following snippet into this file:

// index.js

console.log('hello from Node.js')  

To run this file, you should open up your terminal again and navigate to the directory in which you placed index.js.

Once you successfully navigated yourself to the right spot, run your file using thenode index.js command. You can see that it will produce the same output as before - printing the string directly into the terminal.

Modularization of Your Application

Now you have your index.js file, so it is time to level up your game! Let's create something more complex by splitting our source code into multiple JavaScript files with the purpose of readability and maintainability. To get started, head back to your IDE (Atom, Sublime, Code - you name it) and create the following directory structure (with empty files), but leave the package.json out for now, we will generate it automatically in the next step:

├── app
|   ├── calc.js
|   └── index.js
├── index.js
└── package.json

Every Node.js project starts with creating a package.json file - you can think of it as a JSON representation of the application and its' dependencies. It contains your application's name, the author (you), and all the dependencies that is needed to run the application. We are going to cover the dependencies section later in the Using NPM chapter of Node Hero.

You can interactively generate your package.json file using the npm init command in the terminal. After hitting enter you will asked to give several inputs, like the name of your application, version, description and so on. No need to worry, just hit enter until you get the JSON snippet and the question is it ok?. Hit enter one last time and viola, your package.json has been automatically generated and placed in the folder of your application. If you open that file in your IDE, it will look very similar to the code snippet below.

{
  "name": "@risingstack/node-hero",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC"
}

It's a good practice to add a start script to your package.json - once you do that as shown in the example above you can start your application with the npm start command as well. It comes really handy when you want to deploy your application to a PaaS provider - they can recognize it and start your application using that.

Now let’s head back to the first file you created called index.js. I recommend to keep the this file very thin - only requiring the application itself (the index.js file from the /app subdirectory you created before). Copy the following script into your index.js file and hit save to do this:

// index.js

require('./app/index')  

Now it is time to start building the actual application. Open the index.js file from the /app folder to create a very simple example: adding an array of numbers. In this case the index.js file will only contain the numbers we want to add, and the logic that does the calculation needs to be placed in a separate module.

Paste this script to the index.js file in your /app directory.

// app/index.js
const calc = require('./calc')

const numbersToAdd = [  
  3,
  4,
  10,
  2
]

const result = calc.sum(numbersToAdd)  
console.log(`The result is: ${result}`)  

Now paste the actual business logic into the calc.js file that can be found in the same folder.

// app/calc.js
function sum (arr) {  
  return arr.reduce(function(a, b) { 
    return a + b
  }, 0)
}

module.exports.sum = sum  

To check if you’d succeeded, save these files, open up terminal and enter npm start or node index.js. If you did everything right, you will get back the answer: 19. If something went wrong, review the console log carefully and find the issue based on that.

Download the whole Node Hero series as a single pdf

Next up

In our next chapter called Using NPM we are going to take a look on how to use NPM, the package manager for JavaScript.

Subscribe to our newsletter for updates.

In the meantime, a quick challenge for you: write a small application that asks the user for two numbers to enter from the standard input and print the result after it. (hint: use the readline module: https://nodejs.org/api/readline.html)