Node Package 101- 2 mins
This is a short note about how to get started with node package. Specifically, create an npm package which will install a
warm command, and you can pass arguments with this command, for example:
Step 1 - Create an npm package
Let’s see how it works:
$node -e 'console.log(require("./index"))'
or you can require the directory(which will use the value of “main” as default file):
$node -e 'console.log(require("./"))'
Here is the tricky part for me, since we all use
var somePlugin = require("somePlugin") after npm install, we would expect to use require with the package name directly, that’s where npm link comes in handy. The api doc is self-explanatory itself, the key here is the symbolic link to the current folder:
/usr/local/lib/node_modules/warm -> /Users/fengshuo/Documents/dev_fs/nodeTemp/warm
One thing to notice is the export PATH, if you ever counter something wrong with npm link, check your
~/.bashrc file, add
'export NODE_PATH=/usr/local/lib/node_modules', and don’t forget to
Now, you can require your package by its name directly.
npm unlink -g warm;
Step 2 - Provide commands
In addition to providing a package, it is quite often for us to write a package with command just like the example in the very beginning.
npm provides us with the convenience to do this by modifying the
bin field in package.json, such as:
Basically, this will create a symlink, from your index.js file to
/usr/local/bin/npm where our system check for any terminal commands.
There are a few tips for creating executable files:
#!/usr/bin/env node //other things like require your previous package here
$ chmod a+x ./index.js to make it executable
let’s do npm link again, getting:
Now you can use the ‘warmwhere’ command.
Step 3 - Handle command arguments
To handle arguments, the native process.argv is available, but the minimist package is also easy to use, just use minimist to handle command arguments.
That’s it for local development boiler template. Upload package to npm registry if you want to share it.