Monday, September 30, 2013

optimist is for option parsing in the Node.js space

I am looking at a project right now where variables are defined for Node consumption in an Ant build script like so:

<exec executable="${node.exec}">
   <arg value="${stuff.root}/folderholdingapackagedotjsonfile" />
   <arg value="--user=${stuff.user}" />
   <arg value="--password=${stuff.password}" />
   <arg value="--tag=${build.number}" />
</exec>

 
 

folderholdingapackagedotjsonfile would contain a package.json with a main specification which will direct to a .js holding something like this:

'use strict';
var argv = require('optimist')
   .usage('Usage: node folderholdingapackagedotjsonfile --url [url] --user [email] --password
      [str] --tag [str]')
   .default('url', 'http://www.example.com/')
   .demand(['user', 'password', 'tag', 'statusFilter', 'categoryFilter'])
   .describe('user', 'its your username')
   .describe('password', 'its your password')
   .describe('tag', 'its your version')
   .describe('url', 'its your locale')
   .argv;
var thingtodeferto = require('./somethingelse');
var settingstohandoff = {
   url: argv.url,
   user: argv.user,
   password: argv.password,
   tag: argv.tag
};
thingtodeferto.run(settingstohandoff);

 
 

Our .js file is thus able to kick off a process in somethingelse.js in the same folder as itself and package.json by pushing the variables from Ant into the "run" function in the form of settingstohandoff. Note that while we do not hand in a url from Ant, we could do so.

No comments:

Post a Comment