开发者

node.js javascript for cli apps

As per this question:

node.js image compression

I'm trying to r开发者_JS百科un pulverizer in node.js, in code.

How do I use command line commands inside node.js?

Thanks.


Pulverizr is a node module like any other, so once you have it installed, you 'require' the module as usual. The command line part, cli.js, isn't special. All it does is parse command line arguments, and then 'require' the standard module file and call the 'compress' method.

var pulverizr = require('pulverizr');
var options = {
  dry: false,       // dryrun test  
  quiet: false,     // force quiet run
  recursive: false, // Run recursively
  verbose: false    // Run verbosely
};
var inputs = [ 'somefilename.jpeg', 'secondfilename.png' ];

var job = pulverizr.compress(inputs, options);

I don't know beyond that, you'll have to check it out. And 'options' are optional.


Your question is a bit confusingly phrased. You could have asked one of three things.

How do I call shell commands from inside a Node.js program?

See http://nodejs.org/api/child_process.html

It's not as lightweight as say PERL, but Node has decent support for this:

var exec = require('child_process').exec,
  child = exec('cat *.js bad_file | wc -l',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

For more control over stdin / stdout, look at the "spawn" function which is what exec is built on.

How do I run my code from the command-line / parse-args / etc?

There are a couple of modules for doing this. I've been using commander.js, though for my biggest CLI project, I pretty heavily extended the commander.js logic (see next answer).

How do I use Javascript from the command-line

See underscore-cli - I wrote this, so I'm a bit biased, but it's a really powerful tool for getting easy access to Javascript functionality from the command-line. The intro goes over why out-of-the-box Node.js is really horrible for command-line work, and why my tool makes it much easier. I've put a lot of work into polishing that tool and giving it excellent documentation. It's still under active development, so file a github issue if you want to see any new features.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜