Updating all npm packages in a Node.js project

U

I have two common scenarios where I want to update my npm packages. First, my existing project needs a package update or secondly I’ve started a new project and since I’m lazy I’ve copied my package.json file from one project to this project. I’ve found two different ways to perform this.

  1. Changing the versions to * in my packages.json
  2. Using the npm-check-updates package

Let’s examine in more details each way.

Updating npm package.json version with *

Here is a common package.json file:

[code]
“dependencies”: {
“express”: “~3.2.0”,
“mongodb”: “~1.2.14”,
“underscore”: “~1.4.4”,
“rjs”: “~2.10.0”,
“jade”: “~0.29.0”,
“async”: “~0.2.7”
}
[/code]

A lot of these libraries are now out-of-date from when I started my first project, so if I change all versions to * as follows:

[code]
“dependencies”: {
“express”: “*”,
“mongodb”: “*”,
“underscore”: “*”,
“rjs”: “*”,
“jade”: “*”,
“async”: “*”
}
[/code]

I can then run: npm update –save. Because I’ve added the –save option my package.json file will automatically replace the * with the version that it was updated to. This is good because I wouldn’t want to accidentally update my packages without reviewing the changes first.

Updating package.json with npm-check-updates

As always when you want to do something, someone has probably already done it first. In this case there is a good package called npm-check-updates that will perform a similar process to above without manually changing your package.json file.

With this package you can do the following:

[code]
npm install -g npm-check-updates

ncu -u

npm install
[/code]

The first line of code installs the package in your project. Next you run the command that shows you what packages are available to upgrade with your version to the updated version. Finally you install them.

About the author

By Jamie

My Books