Learning to add dependencies

Exclusive offer: get 50% off this eBook here
Instant Node Package Manager [Instant]

Instant Node Package Manager [Instant] — Save 50%

Create your own node modules and publish them on npm registry, automating repetitive tasks in between with this book and ebook

$14.99    $7.50
by Juzer Ali | October 2013 | Open Source Web Development

This article by Juzer Ali, the author of Instant Node Package Manager, has been specially created to provide you with all the information that you need to set up with node.js and npm. You will learn the basic usage of node package manager, get started with adding dependencies, and modularizing code in different files and folders.

(For more resources related to this topic, see here.)

Adding dependencies

We suddenly realize that for our purposes, we will also need a function in our simplemath library that calculates greatest common divisor (gcd) of two numbers. It will take some effort to write a well-tested gcd function, why not look around to see if someone has already implemented it. Go to https://npmjs.org and search for gcd. You will get scores of results. You may find lots of node modules solving the same problem. It is often difficult to choose between seemingly identical node modules. In such situations, check out the credentials of the developer(s) who are maintaining the project. Compare the number of times each module was downloaded by users. You can get this information on the package's page on npmjs at https://npmjs.org/package/<pkg-name>.

You can also check out the repository where the project is hosted, or the home page of the project. You will get this information on the npmjs home page of the module. If it isn't available, this probably isn't the module you want to use. If, however, it is available, check out the number of people who have starred the project on github, the number of people who have forked it, and active developers contributing to the project. Perhaps check out and run the test cases, or dive into the source code.

If you are betting heavily on a node module which isn't actively maintained by reputed developers, or which isn't well tested, you might be setting yourself up for a major rework in the future.

While we search for the gcd keyword on npmjs website we come to know that there is a node module named mathutils (https://npmjs.org/package/mathutils) that provides an implementation of gcd. We don't want to write our own implementation especially after knowing that someone somewhere in the node community has already solved that problem and published the JavaScript code. Now we want to be able to reuse that code from within our library.

This use case is a little contrived and it is an overkill to include an external library for such simple tasks as to calculate GCD, which is as a matter of fact, very few lines of code, and is popular enough to be found easily. It is used here for the purpose of illustration.

We can do so very easily. Again npm command line will help us reduce the number of steps.

$npm install mathutils --save

We have asked npm to install mathutils and the --save flag, in the end saves it as a dependency in our package.json file. So the mathutils library is downloaded in node_modules folder inside our project. Our new package.json file looks like this.

{ "name": "simplemath", "version": "0.0.1", "description": "A simple math library", "main": "index.js", "dependencies": { "mathutils": "0.0.1" }, "devDependencies": {}, "scripts": { "test": "test" }, "repository": "", "keywords": [ "math", "mathematics", "simple" ], "author": "yourname <yourname@email.com>", "license": "BSD" }

And thus, mathutils is ready for us to use it as we please. Let's proceed to make use of it in our library.

  1. Add the test case: Add the following code to test gcd function to the end of tests.js file but before console.info.

    assert.equal( simplemath.gcd(12, 8), 4 ); console.log("GCD works correctly");

  2. Glue the gcd function from mathutils to simplemath in index.js.

    var mathutils = require("mathutils"); to load mathutils? var simplemath = require("./lib/constants.js"); simplemath.sum = require("./lib/sum.js"); simplemath.subtract = require("./lib/subtract .js"); simplemath.multiply = require("./lib/multiply.js"); simplemath.divide = require("./lib/divide.js"); simplemath.gcd = mathutils.gcd; // Assign gcd module.exports = simplemath;

We have imported the mathutil library in our index.js and assigned the gcd function from the mathutil library to simplemath property with the same name. Let's test it out. Since our package.json is aware of the test script, we can delegate it to npm.

$ npm test … All tests passed successfully

Thus we have successfully added a dependency to our project.

The node_modules folder

We do not want to litter our node.js application directory with code from external libraries or packages that we want to use, npm provides a way of keeping our application code and third party libraries or node modules into separate directories. That is why the node_modules folder. Code for any third-party modules will go into this folder. From node.js documentation (http://nodejs.org/api/modules.html):

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached.

For example, if the file at '/home/ry/projects/foo.js' called require ('bar.js'), then node would look in the following locations, in this order:

  • /home/ry/projects/node_modules/bar.js
  • /home/ry/node_modules/bar.js
  • /home/node_modules/bar.js
  • /node_modules/bar.js

This allows programs to localize their dependencies, so that they do not clash.

Whenever we run the npm install command, the packages get stored into the node_modules folder inside the directory in which the command was issued.

Each module might have its own set of dependencies, which are then installed inside node_modules folder of that module. So in effect we obtain a dependency tree with each module having its dependencies installed in its own folder. Imagine two modules, on which your code is dependent, uses a different version of a third module. Having dependencies installed in their own folders, and the fact that require will look into the innermost node_modules folder first, affords a kind of safety that very few platforms are able to provide. Each module can have its own version of the same dependency. Thus node.js tactfully avoids dependency-hell which most of its peers haven't been able to do so far.

Summary

In this article you will learn how to install node.js and npm, modularize your code in different files and folders, create your own node modules and add them on npm registry, and configure the local npm installation to provide some of your own convenient default.

Resources for Article:


Further resources on this subject:


Instant Node Package Manager [Instant] Create your own node modules and publish them on npm registry, automating repetitive tasks in between with this book and ebook
Published: September 2013
eBook Price: $14.99
See more
Select your format and quantity:

About the Author :


Juzer Ali

Juzer Ali was born and brought up in a small Indian town of Mhow near Indore, Madhya Pradesh. After finishing school in Mhow he took up an Electronics and Telecommunication Engineering course at Devi Ahilya Vishwa Vidyalaya, Indore. During his college days, irrespective of his branch of study, he was always interested in learning computer programming.

After graduating he worked for two and a half years at Tata Consultancy Services (TCS) as a full stack engineer. It was during this tenure that Juzer came across node.js technology and started exploring it. Juzer has made some open source contributions and is a co-maintainer of nodeelasticsearch- client project and the author of crawl.js and expressive-router node modules. He tried to spread JavaScript best practices and evangelize node.js at TCS. Currently he is working as a node.js consultant with a multinational company.

Although he was inclined towards writing since childhood, he never undertook serious writing on a technical subject before this book. He has been writing short fiction stories on his blog since adolescence.

Books From Packt


Node Cookbook
Node Cookbook

Node Cookbook Second Edition
Node Cookbook Second Edition

Using Node.js for UI Testing
Using Node.js for UI Testing

CoffeeScript Programming with jQuery, Rails, and Node.js
CoffeeScript Programming with jQuery, Rails, and Node.js

Node Security
Node Security

Instant Node.js Starter [Instant]
Instant Node.js Starter [Instant]

SolarWinds Orion Network Performance Monitor
SolarWinds Orion Network Performance Monitor

Node Web Development - Second Edition
Node Web Development - Second Edition


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software