Socket
Socket
Sign inDemoInstall

main

Package Overview
Dependencies
8
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    main

Provides useful tools for writing command line scripts


Version published
Weekly downloads
1.3K
increased by42.5%
Maintainers
1
Install size
312 kB
Created
Weekly downloads
 

Readme

Source

node-main

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')). View the example directory for sample use cases.

Installation & Usage

npm install --save main

require('main')(module)

Once required, you can chain the functions below.

Note that the module part is required. This is to properly allow nesting of modules. e.g.

  • script1 contains require('main')(module)
  • script2 requires script1, and implements it's own require('main')(module).

We expect that when running script2 from the command line that it will only call the main function of script2, and not call the main function of script1.

For the time being, this is required until I or someone else figures out a way around it. Read the caching section of the Node Modules API for more information.

.usage(message [, <line2>, <line>, ...])

An optional message to append to the top of flags that describes how the script should be invoked, e.g.

Usage: ./script [flags] <posArg1> <posArg2>

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

If you need to provide a more detailed usage message that will span over multiple lines, you can do so by providing more arguments. Every argument will be separated by a newline, e.g.

require('main')(module)
.usage(
    'Usage: ./script [flags] <posArg1> <posArg2>',
    ' - Some more usage information',
    ' - Another line of usage information')
.run(/* ... */)

.flags(options)

options follows the optimist format for options, but groups them together, e.g.:

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

.run(fn)

fn is the callback that will be invoked when the script is ran directly from a terminal. fn can take the following parameters:

fn(scriptTools)
  • 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 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. Feel free to use whatever name you like for this variable.

General

$.exit([exitCode])

Exits the running program with the specified exit code. If no code is specified, it will exit with code 0 (success). The script doesn't have to explicitly be exited with this command, e.g.

// both of these are valid and will exit with a status of 0 (success)
require('main')(module).run(function($) { $.cout('Hello World').exit(); });
require('main')(module).run(function($) { $.cout('Hello World'); });
$.stdin(callback) or $.stdin() (promise based)

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.

// read from stdin, write to stdout (callback based)
$.stdin(function(input) { $.out(input); });
// same thing with promises
$.stdin().then(function(input) { $.out(input); })
$.stringify(thing)

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.

$.help

A string holding the help message that was generated from the usage (see above) and any flags provided.

Flags and Arguments

$(positionOrFlag)

Allows easy access to positional arguments or flag values.

./script --name Bill /path/to/file
$(0); // returns the argument in position 0, or '/path/to/file'
$('name'); // returns 'Bill'
$.args

An array holding the positional arguments that this script was invoked with.

$.flags

An object holding the all the values for the flags specified - it does not include arbitrary flags that were not defined. Important Note This does not include aliases, e.g.

require('main')(module).flags({
    foo: { alias: 'f' },
    bar: { alias: 'b' }
})
.run(function($) {
    $.cout($('f')); // valid, returns the value of flag "foo"
    $.cout($('foo')); // valid, returns the same as above
    $.cout($('bar')); // likewise for the "bar" flag.

    $.cout($.flags); // object containing flags indexes by the given flags
});

If the above script is called with ./script -f hello -b world, then the output would be:

hello
hello
world
{ foo: 'hello', bar: 'world' }

This is by design. If all flags, aliases, etc. are needed it's possible to access the raw optimist object's parsed flags & arguments with $.optimist.argv.

Output Helpers

Output helpers print text to the window and can be chained, e.g.

$.cerr('Something failed').exit(1);
$.out(string)

Write something to standard output using process.stdout.write.

$.cout([data], [...])

Write something to standard output using console.log.

$.err(something)

Write something to standard error using process.stderr.write.

$.cerr([data], [...])

Write something to standard error using console.error.

File Operations

All file operations are sync, and some can be chained. Take a look at the examples/fileOps.js file for some use cases.

$.mktemp([options])

Returns a temporary file path - it does not create the file.

The options allow you to specify a prefix, suffix, and a directory. All of these are optional:

// returns a path to a temporary file ending in .txt in the system tmp folder.
$.mktemp({ suffix: '.txt' });
// same as above, but we've specified a custom folder to create this temp file.
$.mktemp({ suffix: '.txt' dir: '/home/nolan/myapp' })
$.mkdir(directoryPath)

Given a path to a directory, it will create it if it doesn't already exist. It will create parent directorys as needed. Works similar to mkdir -p on linux systems.

$.read(fileName)

Reads the contents of a given file. Assumes that the encoding is utf8.

$.write(fileName, data)

Writes data to a given file.

$.append(fileName, data)

Appends data to a given file.

$.rm(fileName)

Removes a given file or directory.

$.walk(directory)

Returns back an array of absolute file paths that exist beneith this directory. e.g.

$.walk('/home/nolan/myapp');
/*
Example return values:

[ '/home/nolan/myapp/FILE1.txt',
  '/home/nolan/myapp/FILE2.txt'
  '/home.nolan/myapp/subfolder/foobar.png' ]
*/

If something went wrong fetching the files in the directory, the script will exit and print the error message.

Assert Statements

Assert statements help with the checking of 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.

$.assert.argsLenEq(1).cout($(0)).exit(); // check for 1 arg, print arg, exit
Arguments

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?
Files
  • $assert.fileExists(fileName) Checks if a file exists. Useful if you want to ensure a file exists before reading from it, e.g.
var fileContents = $.assert.fileExists('foo.txt').read('foo.txt');

Example

To view more examples visit the examples directory.

Refer to the following script as basic.js

#!/usr/bin/env node

exports.sentence = function(name, word1, word2) {
    return name + ', ' + word1 + ' ' + word2 + '.';
};

require('main')(module)
.usage(
    'Create a sentence from flags and positional arguments!',
    '',
    'Usage: node test.js [flags] <word1> <word2>')
.flags({
    n: { alias: 'name', demand: true }
})
.run(function($) {
    // Check that there is two positional arguments, then call the function
    // exports.sentence with the value of flag "name", and the first two
    // positional arguments. Finally, exit the script (optional, read why
    // in the documentation for exit).
    $.assert.argsLen(2).cout(exports.sentence($('name'), $(0), $(1))).exit();
});

Using the module from another script will not execute the code in main:

var basic = require('./basic');
console.log(basic.sentence('Nolan', 'sit', 'down'));

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

> node basic.js --name Nolan sit down
Nolan, sit down.
> $?
0 (success)
> node basic.js
# (prints out help & usage information. name / words are not defined)
> $?
1 (failure)

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.

Keywords

FAQs

Last updated on 29 Oct 2013

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

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