Installing a Node.js package is very easy compared to other programming languages thanks to
npm, the package manager that ships with it. To install a node module, one uses the install command, i.e. installing the popular
npm install undercore
Installing a specific version of a package can be accomplished via appending @ and the version name, i.e.
npm install firstname.lastname@example.org
installs the most current version 1.6.0 of the module as of 06/29/2014. To retrieve information on a package such as the available versions, its maintainers etc., one can simply type
npm info undercore. To find a module via a number of keywords, one can use
npm search <keyword1> <keyword2> ..., which will return a list of packages which match the supplied keywords along with their descriptions.
When creating a new node project, it is a good idea to create a
package.json file in the head directory of the project. This file, which has to be written in JSON format, specifies information about the project such as its dependencies, the contributors, the source repository etc. Luckily, npm includes the
init command which helps oneself in setting up this file. In the head directory of the project, typing
npm init will invoke a helper guiding one through the process of creating this file by answering a series of questions.
When installing a new module, passing the option
--save will ensure that the newly installed module is automatically added to the dependencies in the package.json file, e.g.
npm install jquery --save
For packages which are only required for development and not in production use, there is also the
npm install jquery --save-dev
Packages installed with this option will be appended to the
devDependencies in the
package.json file and won't be installed when downloading the package via
npm install <package-name>. However, they are installed when
npm install is invoked locally in the development directory. This distinction is useful as it allows to have modules only used in development such as testing frameworks like
mocha or build tools like
grunt not getting installed when downloading the package for simple usage.
npm help lists many other commands that are included in npm. Typing npm
help <command-name> opens a browser window with extensive documentation of how the command
Publishing a package on npm is almost as simple as installing one. First, we have to create an account via the command
npm adduser, which prompts one for a user name, email address and password. Given a valid
package.json file, we can then publish a module by invoking the command
npm publish from its head directory.