Last active
November 12, 2021 03:55
-
-
Save psenger/e500d19e8512065ab8c8b796002c8e33 to your computer and use it in GitHub Desktop.
[How to make a Node Module run on Command Line and Required] #JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/local/bin/node | |
| #!/usr/bin/env node | |
| const add = ( first, second ) => { | |
| return parseInt( first ) + parseInt( second ); | |
| } | |
| /** | |
| allows the javascript to be executed like this | |
| [14:08:27]/tmp $ ./add.js 1 2 | |
| 3 | |
| [14:08:27]/tmp $ | |
| or | |
| const add = require('./add'); | |
| console.log( add(1,2) ); | |
| **/ | |
| if ( require && require.main === module ) { | |
| console.log( add( process.argv[2], process.argv[3] ) ); | |
| } else { | |
| module.exports = add; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Example of how to test and behave differently if the command is | |
| * `required` vs called from cli via node as a script. | |
| * | |
| * eg: as a script | |
| * node ./boomboom.js foo | |
| * Hello foo | |
| * | |
| * eg: as a required function | |
| * const boomboom = require('boomboom.js'); | |
| * boomboom('Something') | |
| */ | |
| const doSomething = ( message ) => { | |
| console.log('Hello', message); | |
| } | |
| if ( require.main === module ){ | |
| // running as a script | |
| doSomething( process.argv[2] ); | |
| }else { | |
| // this is being `required` | |
| module.exports = doSomething; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment