Node.js–How to use Node Package Manager (npm) and Underscore

Starting with the Node Package Manager

I start this post by installing Node Package Manager. This is your gateway to Node nirvana. NPM will allow you to leverage 1000s of lines of others code to make your node development efficient.

After installing NPM, we will download the library called underscore. This library has dozens of utility functions. I will walk you through about 12 of them. It will provide a quick background and allow you to start using underscore almost immediately in your code.

In a nutshell, you will learn:

How to install NPM This is the first, mandatory step to Node Nirvana
How to install underscore underscore is the hugely popular library for node to provide functional programming capabilities to your code
How to use underscore I provide 12 detailed examples with copy and pastable code to show how they work.

Helps you install all modules from GitHub.

yu23pjfo


Windows or Mac – It is easy to install npm.exe (Node Package Manager)

Step 1 Navigate to https://npmjs.org/dist/
Step 2 Download npm-1.1.9.zip to a folder that has access to node.exe
Step 3 Unzip npm-1.1.9.zip files to download folder

 

Easy Install for the Node Package Manager https://npmjs.org/dist/

z34nupxq


Let’s run through the most popular packages

Here are the “most used” packages in Node

aiiuh1h5


underscore

The command to install using the node package manager is:

npm install underscore

fbd15dbe

Purpose of underscore

z22mrlzd

To bring functional language capabilities to Node.js. There is tons of wrapper code to help you.

What is a functional language anyway?

Functional languages treats computation as the evaluation of mathematical functions
Avoids state and mutable data
Emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state

underscore01.js

Note the code below loops through the array of numbers (1, 2, 3), calculating an average

It then increments the module level variable tot. Finally, it prints the result.

 // Include underscore library
var _ = require('underscore')._;

// Needs module scope to work
var tot = 0;
var count = 0;
_.each([1, 2, 3], function (num) {
    // increment tot
    tot += num;
    count++;
});
console.log('The average is ' + tot / count); 

image


underscore02.js

Uses map functions to build associative arrays. Notice the callback parameters:

val either 1 or 2
key either 0 or 1. Just starts with 0 and auto-increments
list The associative array itself

Note you can look values in the map using syntax like this:

list[key]

 // Include underscore library
var _ = require('underscore')._;

_.map([1, 2], function (val, key, list) {
    console.log('key is ' + key + ', ' + 'value is ' + val);
    console.log('list[' + key + '] =  ' + list[key]);
});

image


underscore03.js

Notice we provide the keys in this example. So if we say something like list[one] we get the value of 1.

 // Include underscore library
var _ = require('underscore')._;

// Using a map with keys declared. Notice the {} instead
// of []
_.map({ one: 1, two: 2 }, function (val, key, list) {
    console.log('key is ' + key + ', ' + 'value is ' + val);
    console.log('list[' + key + '] =  ' + list[key]);

});

image

underscore04.js – recursive techniques

I show two versions here. The first version uses the underscore library. The second version is hand written.

 // Include underscore library
var _ = require('underscore')._;

var sum = _.reduce([1, 2, 3, 4], function (memo, num) {
    console.log('memo is ' + memo + ' and num is ' +
                 num + ' and total is ' + (memo + num));

    // Simple compounding function
    return memo + num;

}, 0);
console.log('sum is ' + sum);

// You could build it by hand also
var result = compound(4);

console.log('hand written result is ' + result);

// My handwritten version that is recursive
function compound(aNumber) {
    if (aNumber < 0) {
        return 0;
    }
    else if (aNumber == 0) {
        return 0;
    }
    else {
        return (aNumber + compound(aNumber - 1));
    }
}

image

underscore05.js – using reject

Have you ever been rejected? Well this code shows you how to reject a genre of music

 // Include underscore library
var _ = require('underscore')._;

var odds = _.reject(['80s music', '50s music', '90s music'], function (list, iterator) {
    console.log('list is ' + list + ', iterator is ' + iterator);
    return list == '80s music';
});

for (var i = 0; i < odds.length; i++) {
    console.log('odds[' + i + ']=' + odds[i]);
}

image

underscore06.js

The function determines where in the list 35 fits in. It is the

 // Include underscore library
var _ = require('underscore')._;

var lookupnumber = 35;
var listOfNumbers = [10, 20, 30, 40, 50];

var answer = _.sortedIndex(listOfNumbers, lookupnumber);

for (var i = 0; i < listOfNumbers.length; i++) {
    console.log('listOfNumbers    [' + i + ']=' + listOfNumbers[i]);
}
console.log('lookupnumber is ' + lookupnumber + ', answer is ' + answer);

ue4levnc

Javascript itself has a lot of built in power, but not as much

From ScriptPlanet.com you see some examples of Javascript primitives. These are awesome but there’s just a few.

ntto1ern

Array Functions

Underscore07.js – lets you blend arrays together

Let’s you grab the first column out of 3 arrays and glue together.

// Include underscore library
var _ = require('underscore')._;

var stooges = ['moe', 'larry', 'curly'];
var verb = ['has a violence level of ', 'is not violent', 'can be violent'];
var violencelevel = ['very', 'not really', 'kind of'];

var result = _.zip(stooges, verb, violencelevel);

showArray(result);

function showArray(myarray) {
for (var i = 0; i < myarray.length; i++) {
console.log('result [' + i + ']=' + myarray[i]);
}
}

3igvv5kb

Function Functions

These are helper functions. They can enhance ‘this’ pointers or can help with timeouts when call functions.

Underscore07.js – lets you blend arrays together

_bind()

 // Include underscore library
var _ = require('underscore')._;

var stooges = ['moe', 'larry', 'curly'];
var verb = ['has a violence level of ', 'is not violent', 'can be violent'];
var violencelevel = ['very', 'not really', 'kind of'];

var result = _.zip(stooges, verb, violencelevel);

var func = function showArray(myarray) {
    for (var i = 0; i < myarray.length; i++) {
        console.log(this.name + '[' + i + ']=' + myarray[i]);
    }
}

// This means that there will be a this.name property in the function
// with the value of 'result'
func = _.bind(func, { name: 'result' }, result);

// Now call showArray()
func();

image

underscore09.js

Let’s you run a function after the call stack is free. Noice that ‘calling bigJob’ shows up immediately.That is because we differed callking ‘bigJob.’

 // Include underscore library
var _ = require('underscore')._;

_.defer(function () { bigJob(); });
console.log('calling bigJob');


function bigJob() {
    for (i = 0; i < 1000000; i++) {
        for (j = 0; j < 1000; j++) {
        }
    }
    console.log('bigJob has ended');
} 

image 

underscore10.js – using the throttle function

Can’t get it to run less than twice.

 // Include underscore library
var _ = require('underscore')._;

var throttled = _.throttle(bigJob, 1000);

// Will execute only twice
// Can't get it to run once only.
throttled();
throttled();
throttled();
throttled();
throttled();

function bigJob() {
    for (i = 0; i < 1000000; i++) {
        for (j = 0; j < 1000; j++) {
        }
    }
    console.log('bigJob has ended');
} 

image

underscore11.js

Will execute only once.

// Include underscore library
var _ = require('underscore')._;

var justonce = _.once(bigJob);

// Will execute only once
justonce();
justonce();
justonce();
justonce();
justonce();

function bigJob() {
for (i = 0; i < 1000000; i++) {
for (j = 0; j < 10; j++) {
}
}
console.log('bigJob has ended');
}

image

underscore12.js

Enumerating properties and values.

 // Include underscore library
var _ = require('underscore')._;

var customobject = { hottest_pepper: 'habanero', best_sauce: 'putanesca',
    least_healthy: 'alfredo'
}

var properties = _.keys(customobject);
var values = _.values(customobject);

console.log('');
console.log('Displaying properties');
showArray(properties);
console.log('Displaying values');
showArray(values);


function showArray(myarray) {
    for (var i = 0; i < myarray.length; i++) {
        console.log(myarray[i]);
    }
    console.log('');
}

image


Wrap up for now

The next post will continue with some new modules. I recommend doing what I did. I tweaked and combined different examples to learn better how they work together. I plan to post a few more samples on the other modules soon. As always, life is busy. Hope this gets you one step closer to using Node effectively.


Download for Azure SDK