NPM or Node Module Packages

After getting your development environment set up and your fancy schmancy Hello World application running what next?

Let’s say we want to display a nicely formatted version of the current date and time. The current best of breed for date and time handling in JavaScript is called Moment and we can choose to use it either server side or client side. For our purposes here, we’ll use it server side, which means we need to install it into our application.

First we’ll want to create a file called package.json which acts as the main configuration point for the application. One of the things it stores is which NPM packages we have installed and which version of each package we want to use.

From the terminal we can now install moment: 

npm install —save moment

You’ll find the package.json file has been modified to include a dependency for moment and you’ll also see a new folder in your project called node_modules that contains the source code for the package. Rule of thumb is that you’ll never be editing files in that folder.

What we can now do though is start to use the newly imported package in our own code.

So we’ll add some extra code to the line which returns Hello World:

And when that runs in the browser we see something like:

Hello World
The day will end in 8 hours

As I write this there are nearly 75,000 packages available from NPM, so this is where you have to get into the mindset that if you are writing something new, then you are probably not writing something new. Leverage what has already been put out there.

Of course there are always issues. In your dependencies in package.json you’ll see that moment has been added with a version number, something like “^2.6.0”. You can also set this to be “latest”, but this means that whenever you run an “npm install” against your application, that NPM will look to see if a more recent version has been released and upgrade it for you. You need to be very aware of this. I recently ran a general install and found that Express had been upgraded from version 3 to 4. This broke my entire application and I had to roll back in Git to recover. So you have to become highly attuned to the impact of what is being upgraded. Things that are important to you, like Express, you should probably fix the version (by removing the ^ from the dependency), whereas things that are more utility helpers like moment you can probably just change to “latest”.

There is a huge amount more that you can do with NPM and it’s worth reading up on it. It’s probably your biggest friend when getting started with node.