Node Web Development(Second Edition)
上QQ阅读APP看书,第一时间看更新

npm – the Node package manager

Node by itself is a pretty basic system, being a JavaScript interpreter with a few interesting asynchronous I/O libraries. One of the things which makes Node interesting is the rapidly growing ecosystem of third party modules for Node. At the center of that ecosystem is npm. The modules can be downloaded at source and assembled manually for use with Node programs. The npm command gives us a simpler way; npm is the de-facto standard package manager for Node and it greatly simplifies downloading and using these modules. We will talk about npm at length in the next chapter.

The sharp-eyed will have noticed that npm is already installed via all the installation methods already discussed. In the past, npm was installed separately, but today it is bundled with Node.

Now that we have npm installed, let's take it for a quick spin. Hexy is a utility program for printing hex dumps of files. It serves our purpose right now in giving us something to quickly install and try out.

$ npm install -g hexy
npm http GET https://registry.npmjs.org/hexy
npm http 200 https://registry.npmjs.org/hexy
npm http GET https://registry.npmjs.org/hexy/-/hexy-0.2.5.tgz
npm http 200 https://registry.npmjs.org/hexy/-/hexy-0.2.5.tgz
/opt/local/bin/hexy -> /opt/local/lib/node_modules/hexy/bin/hexy_cmd.js
hexy@0.2.5 /opt/local/lib/node_modules/hexy

Adding the -g flag makes the module available globally, irrespective of which directory it is installed in. It is most useful when the module provides a command-line interface, because npm ensures the command is installed correctly for use by all users of the computer.

Depending on how Node is installed for you, that may need to be run with sudo.

$ sudo npm install -g hexy

Once it is installed, you'll be able to run the newly installed program this way:

$ hexy --width 12 ls.js
00000000: 7661 7220 6673 203d 2072 6571 var.fs.=.req
0000000c: 7569 7265 2827 6673 2729 3b0a uire('fs');.
00000018: 7661 7220 6669 6c65 7320 3d20 var.files.=.
00000024: 6673 2e72 6561 6464 6972 5379 fs.readdirSy
00000030: 6e63 2827 2e27 293b 0a66 6f72 nc('.');.for
0000003c: 2028 666e 2069 6e20 6669 6c65 .(fn.in.file
00000048: 7329 207b 0a20 2063 6f6e 736f s).{...conso
00000054: 6c65 2e6c 6f67 2866 696c 6573 le.log(files
00000060: 5b66 6e5d 293b 0a7d 0a [fn]);.}.

Again, we'll be doing a deep dive into npm in the next chapter. The hexy utility is both a Node library and a script for printing out these old style hex dumps.