Complete Beginner’s Guide to Node.js

What is Node.js?
Node.js is a c++ engine built to manipulate OS systems that is scripted using JavaScript. The JavaScript engine is called V8, created by Google, and is the same engine that is used in Chromium (the browser technology powering Google Chrome). In simpler terms, it’s a tool to write server side applications using javascript.

logo

Often there can be confusion about what Node.js really is because in some ways it is very similar to Ruby, Python, PHP, LUA, or even Erlang. They are all c or c++ engines with bindings to a scripting language that can be JIT (Just in Time) compiled. Unlike those however, Node.js isn’t also the name of the scripting language, but instead creates bindings to javascript.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Tutorial source code

You can download the scripts from this tutorial here.

 

Installing Node.js

The easiest way to install Node.js is to just click on the “Install” button on the home page or grab the pre-built installer or binary from the downloadsĀ page.

Up and Running

Once you’ve installed Node.js you should have a command nodeĀ Ā available in your terminal or command prompt. If you are on Windows, it will also install a Node.js Command Prompt window into your start menu. When you start the node executable you will be given a command prompt where you can type JavaScript code to be evaluated. This is very similar to the console that is found in the browser developer tools.

It’s important to note, that unlike the browser, there is no DOM or even window object to work with. You will find some familiar things such as console.logĀ Ā and setTimeoutĀ Ā that are not part of the actual JavaScript language, but for the most part it’s core language that you are working with.

hello node

What node does come built in with instead of the window object is an object called “process”. In fact, if you need to exit the node.js REPLĀ (Read Eval Print Loop), then you need to call process.exit()Ā . In case that it isn’t obvious to you why there is no window object, well, it’s because there is no window! Only a process for the executeable that is managed by your OS. There are many useful attributes and methods attached to the process object such as node version, the version of the v8 javascript engine, and environment variables.

process

For now you can play around typing in javascript like console.log(‘Hello Node!’);Ā Ā but what you’ll want to do most of the time is load external js files and modules.

External Files & Modules

Node can load external js files, typically you will load a js file to start up your application. Create a file called “script.js”, and put the following code inside.

var who = 'World';
var greeting = 'Hello';

who = process.argv[2] || who;

console.log(greeting + ' ' + who);

script

Node.js uses a CommonJSĀ module loading system. Instead of putting all of your code into a single js file you can load separate files using the requireĀ  keyword. This is similar in a way to loading files using the script tag in the browser, except that the modules that are required are loaded from within other javascript files, and the script is not executed against the global context (window).

There are many modules built in to the node executable for access to the low level things such as networking and accessing the file system. When you are working with a built in module, you can simply Ā requireĀ Ā it. For those developed by third parties, you need to download the file first. There are thousands of node modules out there, and so there is another program, NPM (Node Package Manager) that is designed to help find and load them.

Common Uses

Ultimately you can build absolutely anyĀ type of application you want using Node.js as the core. Since you have the full power of integrating low level c++ modules there are no restrictions. Developers have built applications to control drones, MMO Game servers, REST APIs, web browsers, you name it. Some of the most common applications that you’ll find (and likely want to use Node.js for yourself) are HTTP Servers and build tools for software development (particularly web / javascript development).

HTTP Server

The absolute simplest HTTP server code is listed right on the home page of nodejs.org. While the total basics are great, of course you’re going to want to do something a little more complicated and practical. Fortunately, there is a very popular library known as ExpressĀ that is meant to give you all the power of a complicated web server, but still make it simple to setup and get running.

To install Express all it takes are a few simple steps. Create a folder for your project, or go into an existing folder. If there isn’t already a node application initialized there, you can create one using npm initĀ . The tool will prompt you through a series of questions, you should be able to just use the defaults for now, and then it will create a package.json file in your folder. This file serves as the manifest for your application. Once your project has been initialized for node, then run:

npm install express --save

This will not only install the express package in the node_modules folder, but adding the –saveĀ  flag will add the entry to your package.json file as well. This is important because you can easily distribute your application and simply reinstall any dependencies, this way you don’t have to store any of your dependencies in source control either. Later, when you want to install, you can simply run npm installĀ  inside the folder, it will use the dependencies listed in the file.

When developing even simple web pages with HTML5 features, you often need to host them via a web server rather than simply opening the index.html file in your browser. Ajax requests and other advanced features are blocked from scripts running locally by the browser’s security sandbox. It’s easy using Express to setup a simple static file server.

var express = require('express'),
    app = express();

app.use(express.static('public'));

app.listen(3000);

Those lines will setup express to serve any files within the “public” folder (note, the folder relative to the script). Any html, images, css, json, txt, etc will all be accessible via http://localhost:3000Ā The default page that it will look for is index.html. Now you can load things locally without running into cross domain issues (say if you wanted to open a json file locally).

Express is also handy to setup a REST API for your front end development projects. It’s possible to host your back end APIĀ of course, but it’s not always the case. Often times if you are a front end developer, the service API may not be developed by you, or even using Node.js. This doesn’t have to slow down your development however, you can setup a mock server using Express relatively quickly and easily.

var foo = {
    data: [1, 2, 3],
    bar: 'baz'
};

app.get('/api/stuff.json', function(req, res) {
    res.send(foo);
});

You can of course respond to all of the HTTP verbs (GET, POST, PUT, DELETE, etc) as well as use query string parameters and post payloads. This way you can setup the client code to expect a certain API and simply swap out the host. You can also help out the service developer by letting them know what you are expecting on the front. With Express and Node.js you can create a fully featured and robust back end API and also do more traditional server side page rendering. It just depends on how far you want to take it.

Summary

Node.js is such an incredibly powerful tool with infinite possibilities, that we’ve just scratched the surface of what you can do. If you like JavaScript programming there is no better choice available right now to solve problems.

I hope that you have found this guideĀ useful and enjoyable. Please leave any comments and/or questions below.