Socket
Socket
Sign inDemoInstall

main

Package Overview
Dependencies
3
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.0.7 to 0.0.8

examples/bare.js

62

index.js

@@ -0,61 +1,11 @@

var Main = require('./src/Main');
var Main = function(currentModule) {
// ran directly from the cli?
var ranDirectly = !currentModule.parent;
// no need to load optimist if we're not going to use it.
var optimist = ranDirectly ? require('optimist') : undefined;
/*
Invoked from another script as:
var exitFn = function(exitCode, message) {
require('main')(module)
if (arguments.length < 2) {
message = exitCode;
exitCode = 0;
}
`module` isn't a variable... it's a global that exists in every node script.
var writeFn = (exitCode === 0) ? console.log : console.error;
if (message) {
if (typeof message === 'string') { writeFn(message); }
else if (message instanceof Error) {
writeFn(message.message || message);
}
else if (typeof message === 'object') {
try { writeFn(JSON.stringify(message)); }
catch (e) { writeFn(message); }
}
else {
writeFn(message);
}
}
process.exit(exitCode);
};
this.usage = function(message) {
if (ranDirectly) { optimist.usage(message); }
return this;
};
// Load in options for optimist
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;
};
// Run the main function if we're running this script directly
this.run = function(mainFn) {
if (!ranDirectly) { return; }
mainFn(optimist.argv, exitFn, optimist.help());
};
};
/*
@param {object} options - Optimist formatted options
@param {function} mainFn - Function that takes optimist argv
@param {object} currentModule - NodeJS module that we will use
*/

@@ -62,0 +12,0 @@ module.exports = function(currentModule) {

{
"name": "main",
"version": "0.0.7",
"version": "0.0.8",
"main": "index.js",

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

node-main
=========
Runs a block of code if a script is called directly as in calling `node script`. It will *not* call the block of code if the script has been required in another module as in `require('script')`.
Provides useful tools for writing command line scripts. It also ensures that a block of code is only invoked when called directly (as in calling `node script`). It will *not* call the block of code if the script has been required in another module (as in `require('script')`).
node-main utilizes [optimist](https://github.com/substack/node-optimist) for argument parsing and provides other tools that are useful for when working with command line scripts.
Bare bones example:
```javascript
#!/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!');
});
```
## Installation & Usage

@@ -12,3 +20,3 @@

### require('main')(module)
### `require('main')(module)`

@@ -26,3 +34,3 @@ Once required, you can chain the functions below.

### .usage(message)
### `.usage(message)`

@@ -35,3 +43,3 @@ An optional message to append to the top of flags that can describe how the script should be invoked, e.g.

### .flags(options)
### `.flags(options)`

@@ -54,14 +62,60 @@ `options` follows the [optimist format for options](https://github.com/substack/node-optimist#optionskey-opt), but groups them together, e.g.:

```javascript
fn(argv, exit, help)
fn(argv, scriptTools)
```
- `argv` is the parsed [optimist argv object](https://github.com/substack/node-optimist#argv)
- `exit` is a helper function that can be used to exit the script. It follows the form `exit(exitCode, optionalMessage)`. If no exit code if provided, it will exit with 0 (success).
- `help` is the usage information if the need arises to explicitly display it.
- `scriptTools` is a helper that provides tools for working with the command line. See below for it's usage.
## 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.
In the documentation below, the `$` symbol stands for the script tool helper function.
### `$.help`
A variable holding the help message that was generated from the usage & any flags provided.
### `$.exit([exitCode], [printThis])`
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.
Some examples:
```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)
```
### `$.readIn(callback)`
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.
```javascript
// read from stdin, write to stdout
$.readIn(function(input) { $.out(input); });
```
### Output Helpers
#### `$.out(something)` and `$.cout(something)`
Write something to standard output. `$.out` using `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`.
## Example
Refer to the following script as `sentence.js`
To view more examples visit the `examples` directory.
Refer to the following script as `basic.js`
```javascript

@@ -71,6 +125,6 @@ #!/usr/bin/env node

exports.sentence = function(name, word1, word2) {
return name + ',' + word1 + ' ' + word2 + '.';
return name + ', ' + word1 + ' ' + word2 + '.';
};
require('main')(module)
require('../index')(module)
.usage('Usage:\n node test.js [flags] <word1> <word2>')

@@ -80,19 +134,28 @@ .flags({

})
.run(function(argv, exit, help) {
.run(function(argv, $) {
// exit if there aren't two words (positional arguments)
if (argv._.length !== 2) { exit(1, help); }
if (argv._.length !== 2) { $.exit(1, $.help); }
var word1 = argv._[0],
word2 = argv._[1];
exports.sentence(argv.name, word1, word2);
var sentence = exports.sentence(argv.name, word1, word2);
$.exit(sentence); // prints the sentence, exits 0
});
```
Using the module from another script will not execute the code in main:
```javascript
var basic = require('./basic');
console.log(basic.sentence('Nolan', 'sit', 'down'));
```
Running from the terminal ($? indicates exit status):
```bash
> node sentence.js --name Nolan sit down
> node basic.js --name Nolan sit down
Nolan, sit down.
> $?
0 (success)
> node sentence.js
> node basic.js
# (prints out help & usage information. name / words are not defined)

@@ -103,11 +166,5 @@ > $?

Using the module from another script will not execute the code in main:
```javascript
var scriptAbove = require('./scriptAbove');
console.log(scriptAbove.sentence('Nolan', 'sit', 'down'));
```
## Note
When installing, make sure to use the `--save` option and/or specify the version in your `package.json` dependencies. This package is undergoing some heavy changes at the moment and new versions may be radically different from previous releases. This type of business will stop once it reaches 0.1.0.

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc