Socket
Socket
Sign inDemoInstall

main

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

main - npm Package Compare versions

Comparing version 0.0.8 to 0.0.10

4

examples/bare.js
#!/usr/bin/env node
require('../index')(module).run(function(argv, $) {
$.exit('running this as a script!');
require('../index')(module).run(function($) {
$.cout('foo').exit(); // print with console.out, exit 0
});

@@ -12,11 +12,8 @@ #!/usr/bin/env node

})
.run(function(argv, $) {
// exit if there aren't two words (positional arguments)
if (argv._.length !== 2) { $.exit(1, $.help); }
var word1 = argv._[0],
word2 = argv._[1];
var sentence = exports.sentence(argv.name, word1, word2);
$.exit(sentence); // prints the sentence, exits 0
.run(function($) {
$.assert.argsLen(2); // exit if there isn't two words
var word0 = $(0), word1 = $(1); // pull from positional arguments
var name = $('name'); // pull from flags. You can also use $('n') here
var sentence = exports.sentence($('name'), word0, word1);
$.cout(sentence).exit(); // prints the sentence, exits 0
});
#!/usr/bin/env node
require('../index')(module)
.run(function(argv, $) {
$.readIn(function(input) { $.out(input); });
require('../index')(module).run(function($) {
$.stdin(function(input) { // read from standard input
$.out(input); // write to standard output (process.stdout.write)
});
});
{
"name": "main",
"version": "0.0.8",
"version": "0.0.10",
"main": "index.js",

@@ -5,0 +5,0 @@ "scripts": {

@@ -10,6 +10,7 @@ node-main

#!/usr/bin/env node
// won't be called if this module is required from another module!
require('main')(module).run(function(argv, scriptTools) {
scriptTools.exit('running this as a script!');
// won't be called if this module is required from another module
require('main')(module).run(function($) {
$.cout('foo').exit(); // print with console.log, exit 0
});
```

@@ -40,3 +41,3 @@

Flags do not have to be specified in this string. Usage for flags are automatically generated based on the options provided (see below) and will appear after this usage message.
Flags do not have to be specified in this string. Usage for flags are automatically generated based on the options provided and will appear after this usage message (see below).

@@ -49,3 +50,3 @@ ### `.flags(options)`

require('main')(module).flags({
f: { alias: 'flag' },
f: { alias: 'flag', demand: true },
t: { alias: 'secondFlag' },

@@ -62,42 +63,49 @@ d: { demand: true },

```javascript
fn(argv, scriptTools)
fn(scriptTools)
```
- `argv` is the parsed [optimist argv object](https://github.com/substack/node-optimist#argv)
- `scriptTools` is a helper that provides tools for working with the command line. See below for it's usage.
## Script Tools
## `$` Script Tools
When invoking `.run()`, you will have access to the argv and the script tools in it's callback function. These tools allow you to perform short hand for repetitive tasks that come up when working with command line scripts.
When invoking `.run()`, you will have access to some useful tools in it's callback function. These tools ease repetitive tasks that come up when working with command line scripts.
In the documentation below, the `$` symbol stands for the script tool helper function.
In the documentation below, the `$` symbol stands for the script tool helper function. Feel free to use whatever name you like for this variable.
### `$(positionOrFlag)`
Allows easy access to positional arguments, or flag values.
```bash
./script --name Bill /path/to/file
```
```javascript
$(0); // returns the argument in position 0, or /path/to/file
$('name'); // returns 'Bill'
```
### `$.help`
A variable holding the help message that was generated from the usage & any flags provided.
A string holding the help message that was generated from the usage and any flags provided.
### `$.exit([exitCode], [printThis])`
### `$.args`
Exits the running program with the specified exit code and an optional output (`printThis` can be an object, string, error, etc). It will write to stdout if the exitCode is 0 (default), or stderr if the exitCode != 0.
An array holding the positional arguments that this script was invoked with.
Some examples:
### `$.exit([exitCode])`
```javascript
$.exit(); // exits with code 0
$.exit('done!'); // exits with code 0, prints hello to the console (stdout)
$.exit(0, 'done!'); // same as above
$.exit(0, 1); // exits with code 0, and prints "1" to the window (stdout)
$.exit(1); // exit's with code 1
$.exit(127, 'command not found!'); // exits with code 127 (stderr)
$.exit(1, new Error('foo')); // exit 1, prints the errors message (stderr)
```
Exits the running program with the specified exit code.
### `$.readIn(callback)`
### `$.stringify(thing)`
Read from stdin in it's entirety, and return a string once finished. Do not use this if you are dealing with large amounts of data from stdin.
Converts some "thing" that is passed in to a string. If it's an object, it will attempt to call `JSON.stringify` on it. If it's an instance of `Error` it will attempt to get the message of said error.
### `$.stdin(callback)`
Read from stdin in it's entirety, and return a string once finished in a callback. Do not use this if you are dealing with large amounts of data from stdin - look towards streaming solutions.
```javascript
// read from stdin, write to stdout
$.readIn(function(input) { $.out(input); });
$.stdin(function(input) { $.out(input); });
```

@@ -107,10 +115,34 @@

Output helpers print text to the window, and can be chained, e.g.
```javascript
$.cerr('Something failed').exit(1);
```
#### `$.out(something)` and `$.cout(something)`
Write something to standard output. `$.out` using `process.stdout.write` and `cout` uses `console.log`.
Write something to standard output. `$.out` uses `process.stdout.write` and `cout` uses `console.log`.
#### `$.err(something)` and `$.cerr(something)`
Write something to standard output. `$.err` using `process.stderr.write` and `$.cerr` uses `console.error`.
Write something to standard output. `$.err` uses `process.stderr.write` and `$.cerr` uses `console.error`.
### `$.assert`
Helps with the checking basic things. If an assertion fails it will print the usage information followed by the reason the script failed and then exit with a status of 1. All assertions can be chained, e.g.
```javascript
$.assert.argsLenEq(1).cout($(0)).exit(); // check for 1 arg, print arg, exit
```
#### `$.assert.argsLen`
Check for positional arguments length. There is a family of checks available for use:
- `$.assert.argsLen(length)` positional arguments equals length?
- `$assert.argsLenGe(length)` args greater than or equal to length?
- `$assert.argsLenGt(length)` args greater than length?
- `$assert.argsLenLe(length)` args less than or equal to length?
- `$assert.argsLenLt(length)` args less than length?
## Example

@@ -129,16 +161,13 @@

require('../index')(module)
require('main')(module)
.usage('Usage:\n node test.js [flags] <word1> <word2>')
.flags({
n: { alias: 'name', demand: true }
n: { alias: 'name', demand: true } // create flag "n", must be present
})
.run(function(argv, $) {
// exit if there aren't two words (positional arguments)
if (argv._.length !== 2) { $.exit(1, $.help); }
var word1 = argv._[0],
word2 = argv._[1];
var sentence = exports.sentence(argv.name, word1, word2);
$.exit(sentence); // prints the sentence, exits 0
.run(function($) {
$.assert.argsLen(2); // exit if there aren't two words
var word0 = $(0), word1 = $(1); // pull from positional arguments
var name = $('name'); // pull from flags. You can also use $('n') here
var sentence = exports.sentence($('name'), word0, word1);
$.cout(sentence).exit(); // prints the sentence, exits 0
});

@@ -153,3 +182,3 @@ ```

Running from the terminal ($? indicates exit status):
Running from the terminal ($? indicates exit status in bash):

@@ -156,0 +185,0 @@ ```bash

@@ -1,2 +0,2 @@

var script = require('./scriptTools');
var scriptTools = require('./scriptTools');

@@ -6,21 +6,13 @@ var Main = function(currentModule) {

var ranDirectly = !currentModule.parent;
// script tools
var tools = scriptTools(ranDirectly);
// no need to load optimist if we're not going to use it.
var optimist = ranDirectly ? require('optimist') : undefined;
// sets the usage
this.usage = function(message) {
if (ranDirectly) { optimist.usage(message); }
return this;
if (ranDirectly) { tools.updateUsage(message); } return this;
};
// Load in options for optimist
// sets the flags
this.flags = function(flags) {
if (!ranDirectly || !flags) { return this; }
for (var key in flags) {
optimist.options(key, flags[key]);
}
// check for any errors & reset argv
optimist.argv = optimist.parse(process.argv);
optimist.argv._.splice(0, 2); // remove node/script path from pos args
return this;
if(ranDirectly && flags) { tools.updateFlags(flags); } return this;
};

@@ -30,5 +22,3 @@

this.run = function(mainFn) {
if (!ranDirectly) { return; }
script.updateHelp(optimist.help());
mainFn(optimist.argv, script);
if (ranDirectly) { mainFn(tools); }
};

@@ -35,0 +25,0 @@ };

@@ -1,101 +0,184 @@

/*
The help message to return if requested
*/
exports.help = '';
var extend = require('util')._extend;
/*
@param {string} helpMessage - The message to set to the variable "help"
*/
exports.updateHelp = function(helpMessage) {
exports.help = helpMessage;
};
var Tools = function(ranDirectly) {
var self = this;
/*
Converts _something_ to a string for printing purposes
@param {object} thing
*/
var thingToString = function(thing) {
// If it's a string, get out of here!
if (typeof thing === 'string') { return thing; }
self.optimist = ranDirectly ? require('optimist') : undefined;
// Error? Attempt to get the message & return that
if (thing instanceof Error && thing.message) { return thing.message; }
self.help = '';
self.args = [];
// Object? attempt to stringify it
if (typeof thing === 'object') {
try {
var json = JSON.stringify(thing);
return json;
} catch (e) {}
}
self.updateHelp = function() { self.help = self.optimist.help(); };
self.updateArgs = function() {
self.args = self.optimist.argv._ || [];
};
return thing; // we tried
};
self.reloadArgv = function() {
// check for any errors & reset argv
self.optimist.argv = self.optimist.parse(process.argv);
// remove node/script path from pos args
self.optimist.argv._.splice(0, 2);
/*
Exits the running program with the specified exit code and an optional output
(`printThis` can be an object, string, error, etc). It will write to stdout
if the exitCode is 0 (default), or stderr if the exitCode != 0.
self.updateHelp();
self.updateArgs();
};
Some examples:
exit(); // exits with code 0
exit('done!'); // exits with code 0, prints hello to the console (stdout)
exit(0, 'done!'); // same as above
exit(0, 1); // exits with code 0, and prints "1" to the window (stdout)
exit(1); // exit's with code 1
exit(127, 'command not found!'); // exits with code 127 (stderr)
exit(1, new Error('foo')); // exit 1, prints the errors message (stderr)
self.updateUsage = function(message) {
self.optimist.usage(message);
self.updateHelp();
};
Have a look at the source for what is going on.
self.updateFlags = function(flags) {
if (!flags) { return }
for (var key in flags) { self.optimist.options(key, flags[key]); }
self.reloadArgv();
};
@param {integer} exitCode - What code to exit this process with
@param {object} printThis - A string / object to output to the window.
*/
exports.exit = function(exitCode, printThis) {
if (arguments.length < 2) {
printThis = exitCode;
exitCode = 0;
}
var writeFn = (exitCode === 0) ? console.log : console.error;
writeFn(thingToString(printThis));
process.exit(exitCode);
};
/*
Exits the running program with the specified exit code.
/*
Print to standard out (process.stdout)
@param {string} thing - what to print to stdout
*/
exports.out = function(thing) { process.stdout.write(thingToString(thing)); };
@param {integer} exitCode - What code to exit self process with
*/
self.exit = function(exitCode) {
process.exit(exitCode || 0);
};
/*
Print to standard out (console.log)
@param {string} thing - what to print to stdout
*/
exports.cout = function(thing) { console.log(thing); };
/*
Takes _something_ and tries to convert it to a string the best it can.
*/
self.stringify = function(thing) {
// If it's a string, get out of here!
if (typeof thing === 'string') { return thing; }
// Error? Attempt to get the message & return that
if (thing instanceof Error && thing.message) { return thing.message; }
// Object? attempt to stringify it
if (typeof thing === 'object') {
try { var json = JSON.stringify(thing); return json; }
catch (e) {}
}
// The "whatever" case
return thing.toString() || thing;
};
/*
Print to standard error (process.stderr)
@param {string} thing - what to print to stderr
*/
exports.err = function(thing) { process.stderr.write(thingToString(thing)); };
/*
Read from stdin in it's entirety, and return a string once finished.
Do not use self if you are dealing with large amounts of data from stdin.
/*
Print to standard error (console.error)
@param {string} thing - what to print to stderr
*/
exports.cerr = function(thing) { console.error(thing); };
@param {function} callback - Contains the stdin string
*/
self.stdin = function(callback) {
var stdinStr = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) { stdinStr += chunk; });
process.stdin.on('end', function() { callback(stdinStr); });
};
/*
Print to standard out (process.stdout)
@param {string} thing - what to print to stdout
*/
self.out = function(thing) {
process.stdout.write(self.stringify(thing));
return self;
};
/*
Print to standard out (console.log)
@param {string} thing - what to print to stdout
*/
self.cout = function(thing) {
console.log(thing);
return self;
};
/*
Print to standard error (process.stderr)
@param {string} thing - what to print to stderr
*/
self.err = function(thing) {
process.stderr.write(self.stringify(thing));
return self;
};
/*
Print to standard error (console.error)
@param {string} thing - what to print to stderr
*/
self.cerr = function(thing) {
console.error(thing);
return self;
};
/*
Retrieves the value of a positional argument or a flag based on if a number
or a string is provided.
@param {string|number} positionOrFlag
*/
self.getValue = function(positionOrFlag) {
if (typeof positionOrFlag === 'string') {
return self.optimist.argv[positionOrFlag]
}
if (typeof positionOrFlag === 'number') {
return self.optimist.argv._[positionOrFlag];
}
throw new Error('provide a position (number) or a flag (string)');
};
/*
Functions that check for certain conditions
*/
self.assert = {
argsLen: function(length) {
if (self.args.length !== length) {
self.cerr(self.help)
.cerr('Expected ' + length + ' positional arguments')
.cerr('Received ' + self.stringify(self.args)).exit(1);
}
return self;
},
argsLenGe: function(length) {
if (self.args.length < length) {
self.cerr(self.help)
.cerr('Expected at least' + length + ' positional arguments')
.cerr('Received ' + self.stringify(self.args)).exit(1);
}
return self;
},
argsLenGt: function(length) {
if (self.args.length <= length) {
self.cerr(self.help)
.cerr('Expected more than ' + length + ' positional arguments')
.cerr('Received ' + self.stringify(self.args)).exit(1);
}
return self;
},
argsLenLe: function(length) {
if (self.args.length > length) {
self.cerr(self.help)
.cerr('Expected ' + length + ' or less positional arguments')
.cerr('Received ' + self.stringify(self.args)).exit(1);
}
return self;
},
argsLenLt: function(length) {
if (self.args.length >= length) {
self.cerr(self.help)
.cerr('Expected less than ' + length + ' positional arguments')
.cerr('Received ' + self.stringify(self.args)).exit(1);
}
return self;
}
};
}
/*
Read from stdin in it's entirety, and return a string once finished.
Do not use this if you are dealing with large amounts of data from stdin.
@return {function} promise - Contains the stdin string
Allows the use of $(0), and $('flag').
*/
exports.readIn = function(callback) {
var stdinStr = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) { stdinStr += chunk; });
process.stdin.on('end', function() { callback(stdinStr); });
module.exports = function(ranDirectly) {
var tools = new Tools(ranDirectly);
var ret = extend(tools.getValue, tools);
return ret;
};
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc