Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active November 12, 2021 03:55
Show Gist options
  • Select an option

  • Save psenger/e500d19e8512065ab8c8b796002c8e33 to your computer and use it in GitHub Desktop.

Select an option

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
#!/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;
}
/**
* 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