Using npm
The node package manager npm comes with the Node.js installer. npm is used for the command line; to use it, we will need to run a terminal program (a command prompt).
On Windows, we can use the basic cmd.exe
, or alternatively, we can download and install Console from http://sourceforge.net/projects/console/.
On Mac OS X, Terminal.app
can be used to run commands.
On Linux, use your favorite terminal. The default on Ubuntu Linux is the gnome terminal.
Open the terminal and type: npm
. This command runs npm without any parameters. As a result, npm will print a general usage overview listing the available subcommands.
Installing a local package
Let's create an empty directory for our project named test
, navigate to that directory, and install the underscore
library there, using npm. Run the following commands:
mkdir test cd test npm install underscore
The last command will tell npm to run the install
subcommand with the argument underscore
, which in turn will install the package underscore locally. npm will output some progress information as it downloads and installs the package.
When installing a package locally, npm creates a subdirectory in the current directory named node_modules
. Inside that directory, it creates another directory for the installed package. In this case, the underscore package will be placed inside the underscore
directory.
Installing a global package
Some npm packages are designed to be installed globally. Global packages add new functionality to the operating system. For example, the coffee-script package can be installed globally, which will cause the command coffee
to become available on our system.
To install global packages we use the -g switch. Have a look at the following example:
npm install -g coffee-script
On some systems it's necessary to request the administrative privilege to run this program. You can do that by using the sudo
command:
sudo npm install -g coffee-script
npm will download and install coffee-script along with all its dependencies. After the process is complete, we can start using the command coffee
, which is now available on our system. We can now run coffee-script code. Lets say we want to run a simple hello-world script written in-line; we can use the -e
switch for that. Have a look at the following example:
coffee -e "echo 'Hello world'"
To learn more in the global package about npm subcommands, we can use npm's help subcommand. For example, to learn more about the install
subcommand, run the following command:
npm help install
More information about the latest version of npm can be found on the official npm documentation at https://npmjs.org/doc/.