Best Way To Learn Node.js

best way to learn nodejs

In this post we will examine the Best Way To Learn Node.js and we will do so by going to school,! is an incredible resource to learn and reinforce your programming skills. They make use of a concept called “Workshoppers”, which is really an genius idea. A Workshopper is an open source module which is actually a structured lesson plan made available via and installable via NPM – How cool is that?! Well since we just completed installing Node.js, we are actually ready to start some hard core learning. We have one word of caution. Do make sure that you are entirely familiar with the basics of JavaScript before attempting this Node.js tutorial. If you’re ready and know what Node.js is, then we can get started..

Getting Ready: Install Learnyounode

First off, let’s get learnyounode up and running. You will of course need to have NodeJs already installed on your computer. If you’re running windows, you’re in luck since we just did a tutorial on how to install nodejs on windows. If you’re on another, just make sure you have NodeJs installed before beginning. Now on to installing learnyounode on our computer. It will be a cinch, I just know it. Open a command prompt such as the windows command prompt on windows, the terminal on osx, or something like Git Bash for Windows which is what we use in this tutorial.

npm install -g learnyounode

This will automatically install everything you need to get a guided tour of learning Node.js. Learnyounode is a program in and of itself and is hosted as a publicly available repository of software on github. Let’s give full credit to the list of hackers that were generous enough to put together this resource for free: Rod Vagg, Andrey Sidorov, Julián Duque, Lars-Magnus Skog, Tim Inman, Dan Flettre, Leigh Zhu, Lucas F. da Costa, Martin Heidegger, Toshiharu Harada, Eric Douglas, Alejandro Oviedo, Leonardo Nascimento, Christophe Porteneuve, Do Minh Hai, Phung Van Tu, Shim, Chayoung You, and Espen Dalløkken.

To begin your adventure, just type:


Here we go!

1. Hello World

We will waste no time, for we want to dig right in to the best way to learn node.js. From the table of contents menu, we will in fact choose the first challenge: Hello World.
launching learnyounode
learnyounode hello world

Cool! We can see we have some instructions for our task. In fact we need to create a program that writes the text of “HELLO WORLD” to the console. Let’s see if we can do it. We will create a file named program.js in the directory we are running our learnyounode session from.


console.log("HELLO WORLD");

This is not a very big program, but I do think it is what we need! As we can see in the instructions of learnyounode, we can verify a program by simply typing:

learnyounode verify program.js

On typing this message in our console, we find profit!
learnyounode verify programjs

How cool is that?! We are presented of the actual results versus the expected results, a pass or fail indicator, and the official solution to the problem. We are also presented with the number of challenges we have left. This is a very slick program indeed.

We should always review the methods used for each example and for this one we have console.log().

2. Baby Steps

As indicated in the last section, we again type learnyounode to bring us back to the main menu.
learnyounode baby steps

The program keeps track of our progress and we can see that HELLO WORLD is completed and we are now at BABY STEPS. Let us try to complete some baby steps.
learnyounode baby steps instructions

Whoa. We are not in hello world land anymore. In this step, we’ll need a result variable, a looping construct, type coercion, and finally logging the output. Let us try this code.


var result = 0;

for (var i = 2; i < process.argv.length; i++) {
    result += Number(process.argv[i]);


learnyounode verify program.js
learnyounode baby steps solution

This example makes use of process.argv() and console.log().

3. My First I/O!

Moving on, we will now select the third challenge, My First I/O!
learnyounode myfirstio

Exercise 3 provides us with the following instructions:
learnyounode myfirstio instructions

In this example we start interacting with the file system using NodeJS. To do so, we pull in the fs, or file system, module into our Node environment. This gives us access to a wealth of methods for file input and output. The node documentation provides a great overview of how File I/O is handled.

For this we will use the following code:


var fs = require('fs');

var contents = fs.readFileSync(process.argv[2]);
var lines = contents.toString().split('\n').length - 1;


learnyounode myfirstio solution

Learn more about require(‘fs’), fs.readFileSync(), buf.toString() and

4. My First Async I/O!

myfirst async io
learnyounode myfirstio async instructions

This step adds one of the main ideas of Node.js, and that is asynchronous operations. This program needs to use just one asynchronous operation to read a file and provide the count of newlines it has to the console. We will need to make use of fs.readFile() and Callbacks for this. Read this snippet from the official documentation about asynchronous forms of methods:

The asynchronous form always takes a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be null or undefined.

The asynchronous form is referring to the asynchronous version of any given I/O method. This is because require(‘fs’) has both synchronous and asynchronous versions of all the available methods.

Let’s look at the solution.

var fs = require('fs');
var file = process.argv[2];

fs.readFile(file, function (err, contents) {
    var lines = contents.toString().split('\n').length - 1;

learnyounode myfirstio async solution

This example uses require(‘fs’), process.argv(), fs.readFile(), buf.toString(), and console.log().

5. Filtered Ls

learnyounode filtered ls

learnyounode filtered ls instructions

var fs = require('fs');
var path = require('path');

fs.readdir(process.argv[2], function (err, list) {
    list.forEach(function (file) {
        if (path.extname(file) === '.' + process.argv[3]) {

learnyounode filtered ls solution

This example uses require(‘fs’), require(‘path’), fs.readdir(), process.argv(), path.extname(), buf.toString(), and console.log().

6. Make It Modular

learnyounode make it modular

learnyounode make it modular instructions

Things are getting a little bit trickier now. This example demonstrates the concept of making a piece of code modular. The way we do it is to create a new file which does a directory listing along with a filtering function. We can assign an anonymous function to the module.exports object, or use a named function. Then in the first file, we can actually require that newly created module much like we would in other programming languages. This follows the convention of var mymodule = require(‘./mymodule.js’) though the .js portion of the module name is optional in the require statement.

var filterFn = require('./solution_filter.js');
var dir = process.argv[2];
var filterStr = process.argv[3];

filterFn(dir, filterStr, function (err, list) {
    if (err) {
        return console.error('There was an error:', err);

    list.forEach(function (file) {

// solution_filter.js
var fs = require('fs');
var path = require('path');

module.exports = function (dir, filterStr, callback) {

    fs.readdir(dir, function (err, list) {
        if (err) {
            return callback(err);

        list = list.filter(function (file) {
            return path.extname(file) === '.' + filterStr

        callback(null, list)

learnyounode make it modular solution

Our module example made use of module.exports, process.argv(), console.error(), console.log(), require(‘fs’), require(‘path’), fs.readdir(), and path.extname().

7. Http Client

learnyounode make it http client

learnyounode make it http client instructions

The HTTP Client example is the quintessential hello world type demonstration of what makes NodeJs so cool. With just a minimum amount of code, you can build a fully functional HTTP client in Node.js. The HTTP Client example makes use of the Node http core module which you can bring into the project with a simple require(‘http’). From there you will then have access to all of the methods it offers, one of which is http.get(). In addition to this, we are introduced to two new concepts in NodeJs and that is the Stream system and Event system.

var http = require('http');

http.get(process.argv[2], function (response) {
    response.on('data', console.log);
    response.on('error', console.error);

learnyounode make it http client solution

The HTTP client example made use of require(‘http’), process.argv(), response.setEncoding(), response.on(), console.log(), and console.error().

8. Http Collect

learnyounode make it http collect

learnyounode make it http collect instructions

Moving on in our exercises for learning Node.js, we come to the Http Collect example. For this, we will need the node package Buffer List or bl for short. This package definition is as follows:

bl is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them!

We use the third party package to make it easier to deal with collecting a stream of data where you would need to collect that data across several events then append the results together before sending to output. There is a fair amount of tedium involved here so we will be glad to make use of bl. Install it with npm install bl at the command line.

var http = require('http');
var bl = require('bl');

http.get(process.argv[2], function (response) {
    response.pipe(bl(function (err, data) {
        if (err) {
            return console.error(err);

        data = data.toString();

learnyounode make it http collect solution

The Http Collect example made use of require(‘http’), require(‘bl’), process.argv(), response.pipe(), buf.toString(), console.log() and console.error()

9. Juggling Async

juggling async

learnyounod juggling async instructions

Juggling Async in Node is no walk in the park. This is one of the more difficult aspects to deal with, and this exercise is designed to show you how to do it. The concept of counting callbacks is introduced here as it is the fundamental way of managing async when working in Node.js. Packages such as async and after make this task much easier. This example uses the grunt worker approach.

var http = require('http');
var bl = require('bl');
var results = [];
var count = 0;

function printResults() {
    for (var i = 0; i < 3; i++) {


function httpGet(index) {
    http.get(process.argv[2 + index], function (response) {
        response.pipe(bl(function (err, data) {
            if (err) {
                return console.error(err);

            results[index] = data.toString();

            if (count == 3) {


for (var i = 0; i < 3; i++) {

learnyounode juggling async solution

Juggling Async made use of require(‘http’), require(‘bl’), process.argv(), response.pipe(), buf.toString(), console.log() and console.error()

10. Time Server

learnyounode time server

learnyounode time server instructions
Time Servers are in integral part of systems applications and programming, so it is really cool that we see an example of a time server here in Node.js. In this example we create a server that uses Transmission Control Protocol to listen for connections on a given port number. Rather than use the http module, this example uses the net module which is part of the Node core and has all kinds of networking functions built in.

var net = require('net');

function zeroFill(i) {
    return (i < 10 ? '0' : '') + i;

function now() {
    var d = new Date();
    return d.getFullYear() + '-'
        + zeroFill(d.getMonth() + 1) + '-'
        + zeroFill(d.getDate()) + ' '
        + zeroFill(d.getHours()) + ':'
        + zeroFill(d.getMinutes());

var server = net.createServer(function (socket) {
    socket.end(now() + '\n');


learnyounode time server solution

The time server example uses require(‘net’), net.createServer(), socket.end(), and server.listen().

11. Http File Server

learnyounode http file server

learnyounode http file server instructions

This is an example of an HTTP file server. The task is to create one in Node.js that responds with the same text file for every request it gets. Since we’re dealing with HTTP we will of course use the http module of Node core. We’ll also use the file system module to help us create the solution.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'content-type': 'text/plain'});



learnyounode http file server solution

The Http File Server made use of require(‘http’), require(‘fs’), http.createServer(), response.writeHead(), fs.createReadStream(), server.listen(), and process.argv().

12. Http Uppercaser

learnyounode http uppercaser

learnyounode http uppercaser instructions

The goal of the HTTP Uppercaser is as you would expect. It tries to listen for POST requests to the http server, converts any data to uppercase, then returns that modified data in a response to the client making the request. We’ll make use of through2-map to help us along. You can install through2-map by typing npm install through2-map at the command line of your machine.

var http = require('http');
var map = require('through2-map');

var server = http.createServer(function (req, res) {
    if (req.method != 'POST') {
        return res.end('send me a POST\n');

    req.pipe(map(function (chunk) {
        return chunk.toString().toUpperCase();


learnyounode http uppercaser solution

Our Http Uppercaser worked and was made possible by require(‘http’), require(‘through2-map’), http.createServer(), method.method(), response.end(), readable.pipe(), buf.toString(), and server.listen().

13. Http Json Api Server

learnyounode http json api server

learnyounode http json api server instructions

We have made it to the final challenge! This final challenge is to build an HTTP server that servers Javascript Object Notation data upon receiving an HTTP GET request to the path of ‘api/parsetime’. The request will include a query string which has a key of ‘iso’ and a value of an ISO formatted time. This might look something like /api/parsetime?iso=2013-08-10T12:10:15.474Z. There will also be a second endpoint clients can make requests to. This will be for the purpose of parsing unixtime and will live at /api/unixtime. This endpoint will be able to parse the same query string as the first, but it will respond differently. It will respond with UNIX epoch time in milliseconds. This refers to the number of milliseconds that have elapsed since January 1 1970 00:00:00 UTC. A challenging task for sure.

var http = require('http');
var url = require('url');

function parsetime(time) {
    return {
        hour: time.getHours(),
        minute: time.getMinutes(),
        second: time.getSeconds()

function unixtime(time) {
    return {unixtime: time.getTime()}

var server = http.createServer(function (req, res) {
    var parsedUrl = url.parse(req.url, true);
    var time = new Date(parsedUrl.query.iso);
    var result;

    if (/^\/api\/parsetime/.test(req.url))
        result = parsetime(time);
    else if (/^\/api\/unixtime/.test(req.url))
        result = unixtime(time);

    if (result) {
        res.writeHead(200, {'Content-Type': 'application/json'});
    } else {

learnyounode http json api server solution

The Http Json Api Server made use of a myriad of methods including require(‘http’), require(‘url’), http.createServer(), url.parse(), response.writeHead(), server.listen(), and process.argv().

Best Way To Learn Node.js Summary

So was this the best way to learn Node.js or what?! When I found those interactive tutorials by, I knew it was time to get our hands dirty with Node. These interactive lessons really did cover a lot of ground. To be honest, as a new comer to Node myself, I found the exercises to be difficult. Surely with practice and patience, programming in Node will become easier – but it’s great that we covered as much as we did here. Like any other programming library or node framework, it comes down to learning the methods of the classes offered, learning what arguments they expect, and what you can do with them. Node is like taking JavaScript and putting it on steroids. There is a ton it offers, but the learning curve can be fairly steep.

Further Reading

If you find that you just can’t get enough NodeJS learning, then you must continue to these epic resources to further your Node foo.