Ok, so you've built your first module, but now you want to make it use one of the many libraries available via the npm registry.
There are a few ways to find a module. You can use http://npmjs.org or http://npmsearch.com to find modules that may fit what you need.
Modules should have tests, and they should try to only export a single function
You'll develop more criteria as you start digging through more modules, don't be afraid to read their source!
So you've found a module that you want to install, we'll use the request
module to demonstrate how to make it a dependency of your-first-node-module
cd your-first-node-module
npm install --save request
Ok, that should have dumped a bunch of text to your terminal. NPM does a bunch of work to make sure it gets all of the dependencies (recursively!) of the module you are installing
the --save
flag will update your package.json with the version of request
installed
$ cat package.json
{
"name": "your-first-node-module",
"version": "1.0.0",
"description": "very first module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Elijah Insua <[email protected]> (http://tmpvar.com)",
"license": "MIT",
"dependencies": {
"request": "~2.33.0"
}
}
$ npm list
[email protected] /Users/tmpvar/work/tmp/your-first-node-module
└─┬ [email protected]
├── [email protected]
├── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ └─┬ [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├─┬ [email protected]
│ └── [email protected]
└── [email protected]
We'll demonstrate that by using it in the repl
$ cd your-first-node-module
$ node
> var request = require('request')
undefined
> request.get('http://google.com/', function(error, response, body) { console.log(body); })
... whole bunch of data ...
.. pause ..
.. a bunch of html ..
And that's how you use a node module installed from npm
if you need modules to support your tests or local development you can npm install --save-dev
and they will be placed in your devDependencies
section of your project's package.json
.
note: these modules will only be installed when you npm install
from inside of your project. Users of your project will not need to install the development dependencies and npm will ignore them when installing your module as a dependency