Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CLI Tools with Node

CLI Tools with Node

Learn how you can easily create your own CLI (Command Line Interface) tool with Node.js.

Henrique Schreiner

November 02, 2016
Tweet

More Decks by Henrique Schreiner

Other Decks in Programming

Transcript

  1. root@hmschreiner : $ whoami # Henrique Schreiner Software Developer at

    e-Core @hmschreiner linkedin.com/in/HenriqueSchreiner e-core.com/pt/carreiras
  2. root@hmschreiner : ~/my-tool-folder $ npm init name: file-search version: 1.0.0

    description: My CLI tool to search files entry point: index.js test command: git repository: keywords: author: Henrique Schreiner license: (ISC)
  3. { "name": "file-search", "version": "1.0.0", "description": "My CLI tool to

    search files", "main": "index.js", "author": "Henrique Schreiner", "license": "ISC" } Is this ok? (yes) root@hmschreiner : ~/my-tool-folder $ npm init
  4. { "name": "file-search", "version": "1.0.0", "description": "My CLI tool to

    search files", "main": "index.js", "author": "Henrique Schreiner", "license": "ISC", }
  5. { "name": "file-search", "version": "1.0.0", "description": "My CLI tool to

    search files", "author": "Henrique Schreiner", "license": "ISC", "preferGlobal": true, "bin": { "file-search": "index.js" } }
  6. root@hmschreiner : ~/my-tool-folder $ vim index.js #!/usr/bin/env node --harmony 'use

    strict'; console.log('This is the file-search script.');
  7. root@hmschreiner : ~/my-tool-folder $ npm link - Install the script

    on your system - Creates a symlink to your project so that you can run the project whilst working on it - No need to keep reinstalling it over and over again
  8. root@hmschreiner : ~/my-tool-folder $ vim index.js #!/usr/bin/env node --harmony 'use

    strict'; let inputArgs = process.argv.slice(2); let searchPattern = inputArgs[0];
  9. root@hmschreiner : ~/my-tool-folder $ vim index.js #!/usr/bin/env node --harmony 'use

    strict'; const exec = require('child_process').exec; let inputArgs = process.argv.slice(2); let searchPattern = inputArgs[0]; exec(`ls -a | grep ${searchPattern}`, (err, stdout, stderr) => { console.log(stdout); });
  10. root@hmschreiner : ~/my-tool-folder $ npm publish - Ensure a good,

    well written README file - Decide on an initial version number (e.g. 1.0.0) - If you’ve not registered on npm...
  11. root@hmschreiner : ~/my-tool-folder $ npm adduser - Follow the prompts

    to set up and authenticate yourself - Once published, users can then install your module