Enter the World of Node.js

Everyone talks about Node.js these days, but you’re not quite sure what it is? Or, do you just want to impress your friends with some nerd knowledge? This article will take you on a quick ride through the world of Node.js!

Enter the World of Node

Background

On May 27, 2009 Ryan Dahl released the initial version of an open-source software platform written in JavaScript and C++. But why did he name it Node? In the beginning the project, a non-blocking web server, was called web.js. Ryan Dahl soon discovered that a web server was not enough, so he created a foundation to control the interaction between distributed systems called nodes - an event-driven, non-blocking I/O system.

Node applications are developed using JavaScript because Node is based on Google’s open source JavaScript engine, V8. V8 is the same engine that gives Chrome its exceptional JavaScript performance. This allows you to create applications for every device that runs on Linux, MacOS, Windows, or SunOS.

You also get a large library of core and third party Node modules to handle just about any task out there. Core modules come bundled with Node, while third party modules can be installed using Node’s package manager. And, because Node is released under the MIT licence you can use all of this for free!

Modules

Modules can be thought of as the smallest part in a large system. Technically, a single source file is considered a module, but often times multiple files work together to constitute a module (or library). Modules are intended to solve a single problem, and only that problem. Applications can then act as a glue that lets these modules work together.

Node modules

Installing Node

There are multiple ways to install Node on your system. You can build Node from source on any supported system, but it is often simpler to use a package manager or installer.

Windows

Use the automatic installer to install Node.

Linux

Install the node package with your systems default package manager.

Mac

You can use package, Flink, homebrew or macports to install Node.

Is Node Installed?

Open your command line and type node -v. This will print the currently installed version of Node to the terminal window. If you do not see a version number, something has gone wrong, and you should try installing again. You should also verify that Node’s package manager (npm) is installed by typing the command npm -v.

Hello World!

Create a file named hello_world.js. Node allows you to print messages to a terminal using the built-in console.log() function. Add the following code to hello_world.js:

console.log('Hello World');

To execute this program, open a terminal window and change to the directory containing hello_world.js. From that directory, type the command node hello_world. This command invokes Node and tells it to execute the contents of hello_world.js. If everything worked correctly, you should see the message Hello World printed to the terminal.

Core Modules

As previously mentioned, Node ships with a collection of core modules. This section describes three commonly used core modules, but this section is by no means comprehensive.

console

This is similar to the console object functions provided by most web browsers, but the output is sent to the standard output (stdout) or standard error (stderr). You have already seen the console object in action in the Hello World example. It is worth pointing out that console is used by default in every Node application, meaning that you don’t need to explicitly import it. For more information on this module, see:

http

When most people think of Node, they think of web servers. The HTTP module provides a server and client for working with HTTP/HTTPS traffic. Unlike the console object, the http module must be explicitly imported into an application using the require() function (you’ll see an example of this soon). Additional information on the http module is available here:

fs

The fs module provides asynchronous and synchronous functions that interact with the file system. This article will not go into details on the fs module, but curious readers are directed to a previous SitePoint article on the topic. The official Node documentation and source code is also available at the following locations:

A Simple Web Server

The source code for a very simple web server is shown below. This server utilizes the previously mentioned http core module. Save the following code in web_server.js.

// Load the "http" module
var http = require('http');

// Create a HTTP server
// - request comes from the client
// - response goes to the client
http.createServer(function(request, response) {

  // Send the HTTP status code "200 - ok" to the request 
  // and set the content type to "text/plain"
  response.writeHead(200, {'Content-Type': 'text/plain'});

  // Tell the server that everything has been sent to the client
  // so that the server considers this message as complete
  response.end('Hello World');

// Accept connections on port and IP
}).listen(1337, '127.0.0.1');

// Tell the user that the server is up and running
console.log('Server running at http://127.0.0.1:1337/');

Run the server by typing the command node web_server in a terminal window. You can now access the server by opening your favorite browser and navigating to http://127.0.0.1:1337/. You will see our beautiful Hello World message in your browser.

The Node Package Manager

If you want to use more than the core modules, there is no way around using Node’s Package Manager, or npm. npm installs third party modules from its registry which contains over 64,000 modules. As of Node version 0.6.3, npm is bundled and installed automatically, so you can use it right away.

Installing Packages

npm’s most common use case is the installation of modules from the registry. To install a module, issue the command npm install module_name, where module_name is the module’s ID in the registry. For example, to install the Express framework, you would issue the following command:

npm install express

This will install Express in the node_modules subdirectory of your current directory. If you look inside node_modules, you’ll see another directory named express that contains the code for the Express module. You’ll also see another node_modules directory inside of express. This directory contains any modules that Express depends on.

A module that your code relies on is known as a dependency. In our example web server, http is a dependency, but since it’s a core module, we didn’t have to worry about installing it. If your code depends on a third party module, then npm needs to know about it so that it can be installed. Dependency information, along with other meta data about your application is stored in a file named package.json. This file is stored in your application’s root directory, and contains JSON data.

As an example, assume that your project depends on the coffee-script module. You will need to include this in your package.json. Luckily, you can automatically updated package.json when you install a module using the --save argument, as shown below:

npm install --save coffee-script

Of course, you probably don’t have a package.json file yet, so nothing special will happen. We’ll revisit the package.json file shortly. For now, just know that the previous command would create something like this in your package.json:

...
  "dependencies": {
    "coffee-script": "^1.7.1"
  }
...

Creating a Package

To create a package, you only need to create a package.json file. Since this is a plain JSON file, you could write one yourself. However, the file is expected to contain certain fields, and you could easily make a mistake. Therefore, it is recommended that you use the npm init command to automatically generate a package.json. This command will prompt you for the important values. An example of npm init is shown below. The values in parentheses are suggestions provided by npm. You can simply press Enter to accept the suggestion, or type your own value, as shown on the version line.

name: (node-package.json) 
version: (0.0.0) 0.0.1
description: How to create a new package.json
entry point: (index.js) 
test command: 
git repository: (git://github.com/TimPietrusky/node-package.json.git) 
keywords: package, json
license: (ISC) MIT

Once you have completed all of the prompts, a package.json file will be created, containing your project’s name (required), version (required), a description, author(s), keywords, repository, homepage, and other useful data. By providing a package.json file, another developer is able to easily install your module and all of its dependencies. An example package.json file is available in this GitHub repo (and any repo that is published to the npm registry).

These are just the very basics of package.json. If you want to dive into all available attributes you should read the package.json cheatsheet.

Conclusion

This article has provided the absolute basics for working with Node. However, this is just the tip of the iceberg, and Node is one of the fastest growing communities out there. I suggest checking out the official Node project page for links to code, articles, videos, and more. Also be on the lookout for future SitePoint articles covering topics like publishing code to npm, IDEs for Node development, and hosting providers that work with Node.

Want to learn more about this? Our sister company Learnable has a brand-new Node.js course!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • od3n

    very useful and easy to understand!

    • http://timpietrusky.com/ TimPietrusky

      Thanks! It was my main goal to write something that’s very easy to understand, so that more people start using Node.js!

  • Asif Khan

    Useful article for a good glance over node.js

    • http://timpietrusky.com/ TimPietrusky

      Thank you.

  • Иван Брежнев

    I like Node.js, thanks for post =)

    • http://timpietrusky.com/ TimPietrusky

      You are welcome! Node.js is simply awesome.

  • http://www.tungbb.info/ debugger

    I want a like button. Thanks your post

    • http://timpietrusky.com/ TimPietrusky

      Thanks dude! Just share it on every network :D

  • ADIMO

    Very interesting :)

    • http://timpietrusky.com/ TimPietrusky

      Thank you!

  • onlineflowers

    Add glow and happiness on your mothers face on Mother’s Day by sending amazing gifts from different online sites. Order online cheap flower delivery to India and experience a good service.

  • http://timpietrusky.com/ TimPietrusky

    Nice! Would be cool if you could translate some of those articles into english.

  • RadneyAaronAlquiza

    The only thing stopping me from using node.js or any other “push server” is the pricing for hosting commercial projects. You’d need to spend at least $40/month to have 1 dynamo/gear/whatever and a small sized database. I will have to wait for prices to go down a bit more then go with Node.js (which is fantastic).

    OpenShift offers a free hosting but it’s for open source an non-commercial projects.