Marcus Node Bits - npm is not only for getting packages

· February 5, 2014

I’m writing down some of the things I’ve picked up when I started to learn about Node, Express, and Mongo. Here are all the posts in the series:

This post is about the Node Package Manager, npm, and some of its many features.

Node is really cool, but without its package management system, npm, and the plethora of packages out there it would be pretty bland and probably not as well known.

I will not talk much about the packages out there. They are LEGIO and increase each day. Check out https://npmjs.org and be amazed. The packages come ago almost by the hour. Keeping track of what’s hot and what’s not is a near impossible task. I usually look and ask around in my network to find out what is worth using and not.

But the npm tool, let’s talk about that. The most common commands are of course:

  • npm install - installs all the packages listed under dependencies in package.json, into the node_modules folder
  • npm install [thePackage] - installs thePackage into your node_modules folder
  • npm install [thePackage] -g - installs thePackage globally, that is reachable from all the node projects on your machine. This can be useful for tools that you’re running from the command line, like mocha for example. I would recommend that you include all tools needed to run your project in the project local node_modules folder. But don’t check node_modules into git (ignore it in your .gitignore)
  • npm uninstall [thePackage] - well… uninstalls thePackage, of course
  • npm update [thePackage] - updates the package to the latest version on http://npmjs.org

What’s really cool with npm is that it can be extended, as I mentioned in my package.json post. Under the “scripts” node in package.json you can add commands to npm. Here’s an example, an extract of a package.json file:

These lines give you four new subcommands to npm:

  • npm start - will execute “node app.js” and hence start your app. You can imagine other commands for starting, like
  • npm run start_dev - that starts your staging configuration for example
  • npm test - execute the mocha command above. If you need other switches you can just update your package.json.
  • npm run test_watch - is one example that adds the “-w” switch and hence is watching my directory for changes and rerun all the tests in it.

You can of course add as many commands as you like. It’s a really nice feature if you consider the fact that people who bring your code down will have your commands available to them.

Twitter, Facebook