Prerequisits
At first, you need to have some tools installed. Here they are.node.js installed
npm installed
$ apt-get install nodejs $ apt-get install npm
Init your node project
To initialise your project simple type:$ npm init
This will create your package.json
Fill your projectdata
My package.json looks like that
{ "name": "simplecommand", "version": "1.0.0", "description": "a simple console command", "main": "createUser.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/pboethig/nodejs-lessons.git" }, "keywords": [ "nodejs", "command" ], "author": "pboethig", "license": "MIT", "bugs": { "url": "https://github.com/pboethig/nodejs-lessons/issues" }, "homepage": "https://github.com/pboethig/nodejs-lessons#readme" }
Add you command script
Get you node.js pathwhich nodeThis could output:
/usr/bin/node
Create a file "createUser.js" and add the shebang to it
!#/usr/bin/env nodeThis will tell the system to use node.js to execute your script
Make your script executable
chmod a+x createUser.js
Tell npm to install your command
Edit your package.json and add the bin object
{ "name": "simplecommand", "version": "1.0.0", "description": "a simple console command", "main": "createUser.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/pboethig/nodejs-lessons.git" }, "keywords": [ "nodejs", "command" ], "author": "pboethig", "license": "MIT", "bugs": { "url": "https://github.com/pboethig/nodejs-lessons/issues" }, "bin": { "createUser": "createUser.js" }, "homepage": "https://github.com/pboethig/nodejs-lessons#readme"
Everytime you modifiý your command, you have to run the global installer
npm install -g
Install commander
To get your command running, we need the commander library, wich does the whole parsing thing for us,npm install --save commander
Add you command code to the scriptfile
Open your createUser.js and add a simple command#!/usr/bin/env node var program = require('commander'); program .version('0.0.1') .usage('<username>') .parse(process.argv); if(!program.args.length) { program.help(); } else { console.log('Username: ' + program.args); }As you can see, we are requiring the commander lib, add an option "username" and parse the input on the terminal.
If no argument was set, we display the helpfile.
If the username was given, we are outputting the username. And we succeed
Instead of that simple sample, you can implement your complex logic here.
That's it. Now you can run your command after you have installed your final scriptversion
$ npm install -g createUser.js
$ createUser
This will output the helpfile of your new command. Nice !
Keine Kommentare:
Kommentar veröffentlichen