DailyJS

DailyJS

The JavaScript blog.


Tagcommand-line
Featured

node command-line servers libraries

Add a CLI to Node Apps with Vantage

Posted on .

Vantage (GitHub: dthree/vantage, License: MIT, npm: vantage) by David Caccavella is a very nicely packaged module for adding command-line interfaces to your Node applications. It provides two components: a server, and a command-line tool that you use to connect to your live app. Rather than connecting to a TCP port with something like telnet, you actually type vantage in the command-line.

To hook it up to your application, you'll need to add a Vantage server. First, install Vantage to your project (npm install --save vantage), then instantiate a Vantage object and hook up the functionality that you want:

var Vantage = require('vantage');  
var server = new Vantage();

server  
  .command('foo')
  .description('Outputs "bar".')
  .action(function(args, cb) {
    // Do anything: check the database, run migrations, show useful stats
    console.log('bar');
    cb();
  });

server  
  .delimiter('webapp~$')
  .listen(80)
  .show();

I'd put this in a separate file to your main Express/Koa/Hapi/etc. app server, then add Vantage actions for the desired functionality. You could add things like database queries, or heartbeat/usage info, and so on.

Once you've added Vantage to your web app, if you install it globally you'll be able to just type vantage ip:port to connect to your server. Typing help will display the built-in commands and any actions that you've added. You should see something like this for the previous example:

webapp~$ help

  Commands

    help [command]    Provides help for a given command.
    exit [options]    Exists instance of Vantage.
    vantage [server]  Connects to another application running vantage.
    foo               Outputs "bar".

In addition to basic commands and subcommands, Vantage uses inquirer for prompts. Inquirer's prompts are quite powerful: they're ideal for things like yes/no questions and checkboxes. You could use it to force a "yes/no" prompt before a irreversible operation.

Vantage has a few other nice features that'll make your backdoor feel more professional: you can add a banner when people sign in (perhaps with legal warnings, or help), it supports a "firewall" for limiting access, and the documentation has details for using Vantage with Express, Koa, and TLS/SSL.

On the subject of backdoors: Vantage doesn't currently support authentication. It may be possible to use it as a limited informational interface to your server, but I'd strongly recommend binding to internal interfaces only. That means you'd have to ssh to a server, and then run vantage remotely. If that's not possible or convenient, then at least set up TLS/SSL. The current idea for authentication is to support it through middleware -- it already supports middleware so actions can be made reusable, so it seems like a sensible approach.

Authentication issues aside, it definitely seems like something worth using for development servers: I know many people who would love to see their Node web apps get the kind of consoles that popular web frameworks offer (Django's manage.py shell and Rails' console are two that spring to mind). Check it out, but try local/development mode first!

Featured

libraries node modules WebSocket command-line gulp build-tools chat

Node Roundup: nchat, hulken, cult

Posted on .

nchat

nchat (GitHub: irrationalistic/nchat, npm: nchat) by Chris Rolfs is a terminal-based chat application that uses WebSocket, which means it's easier to use on networks where IRC might be blocked.

Notifications are supported on Mac OS X, and the client can run as the server so you only need to install nchat itself. It supports a few IRC-style commands, like /users, and you can deploy it to hosting providers like Heroku.

hulken

Hulken (GitHub: hulken, License: MIT, npm: hulken) by Johan Hellgren is a stress testing tool for HTTP services. It can make GET and POST requests, and can be configured to send dynamic payloads.

You can use hulken as a command-line tool, or a Node module. The documentation includes all of the supported options, and you'll need to write an options.json file to use it on the command-line.

cult

Cult (GitHub: typicode/cult, License: MIT, npm: cult) is a tool that monitors changes to a gulpfile and then reloads Gulp. You can run it on the command-line, and it uses the chalk library for pretty output. The readme has an example for supporting gulpfiles that are split across multiple files.

Featured

libraries validation node modules command-line

Node Roundup: 0.10.35, Prettiest, Artisan Validator

Posted on .

Node 0.10.35

Node 0.10.35 was released today, which has some changes to timers relating to the unref behaviour:

  • timers: don't close interval timers when unrefd (Julien Gilli)
  • timers: don't mutate unref list while iterating it (Julien Gilli)

This was released soon after 0.10.34, which updated v8, uv, zlib, and some core modules including child_process and crypto.

Prettiest

What if you want to prevent a command-line script from executing more than once? Prettiest (GitHub: punkave/prettiest, License: MIT, npm: prettiest) from P'unk Avenue LLC combines data storage and locking, and should work well for Node command-line scripts made with modules like ShellJS.

This is the simplest example -- it will track how many times it has been run:

var data = require('prettiest')();

data.count = data.count || 0;  
data.count++;  
console.log('I have been run', data.count, ' times.');  

I've often wanted to persist data in command-line scripts, but didn't want to bother with sqlite or JSON file serialisation, so this seems ideal for such cases. And even if you want the locking behaviour, your scripts can still be asynchronous.

Artisan Validator

Connor Peet is on a quest to create a simple and well-documented data validator for Node. Artisan Validator (GitHub: MCProHosting/artisan-validator, License: MIT, npm: artisan-validator) allows you to define rules that get validated against objects, so you can easily hook it into a Node web application:

var validator = require('artisan-validator')();  
var rules = {  
  username: ['required', 'between: 4, 30', 'alphanumeric'],
  password: ['required', 'longer: 5'],
  acceptTOS: ['required', 'boolean: true']
};

validator.try(req.body, rules).then(function (result) {  
  if (result.failed) {
    res.json(400, result.errors);
  } else {
    registerAccount();
  }
});

You can add custom validators with validator.validators.add, but there are quite a few built-in rules that cover JavaScript types, and various string and date formats. The error messages can be localised as well.

Featured

testing node modules command-line substack node-web

Node Roundup: 0.11.8, tabby, Nixt

Posted on .

Node 0.11.8

The core developers are cranking the handle again and firing out releases. Today Node 0.11.8 was released, which upgrades uv and V8. There's a new buf.toArrayBuffer API, debugger improvements, and core module fixes.

I saw 0.11.8 announced on Twitter, and the author hinted at more frequent unstable releases.

tabby

If it's not TJ Holowaychuk it's Substack. I don't believe it's possible to write a weekly column about Node without mentioning one of them at least once. Substack just released a client-side project called tabby (GitHub: substack / tabby, License: MIT, npm: tabby), a module for creating web applications with tabs using progressive enhancement techniques.

Why is this notable? Well, Substack has been ranting about Node's module system and client-side code. He wants you to stop mucking about and require(). Tabby blends the browser and Node by using WebSockets, and makes judicious use of Node's core modules and streams.

For something focused on client-side code, it uses an interesting cocktail of modules. The inherits module provides browser-friendly inheritance, whilst still being compatible with util.inherits. And trumpet is used for parsing and transforming streaming HTML using CSS selectors. In the documentation, Substack recommends using hyperspace for rendering.

Looking through the examples, it definitely feels like idiomatic Node. I can imagine this style scaling up well to a larger web application.

Nixt

Nixt

Test code readability can bring huge gains when maintaining projects. Tests should communicate intent, and the longer they don't need heavy modification the happier everyone will be. I generally find myself writing DSL-like methods for tests that reduce code duplication, particularly in the set-up phase.

With that in mind, it's interesting to see Nixt (GitHub: vesln / nixt, License: MIT, npm: nixt) by Veselin Todorov. This is a module for testing command-line applications. It's based around expectations, which reminds me of good old Expect.

Nixt works well asynchronously because it supports middleware for ordering execution. It can be used with a test harness like Mocha, and allows you to define custom expectations, which is where your application-specific DSL-like test helpers come in.

Although I'm probably guilty of using Node for command-line scripts that could be done with a shell script (I write my share of shell script too though), Nixt seems like a great way to test them, particularly as people often forget to test such scripts.

Featured

events node modules bower command-line

Node Roundup: CampJS, bower-registry, Helmsman

Posted on .

You can send in your Node projects for review through our contact form.

CampJS

CampJS August

CampJS will be held in the Gold Coast, Australia, on August 9th to 12th. TJ Holowaychuk will be attending, and also Angelina Fabbro.

If you're interested, tickets start at AU$320. DailyJS readers can get a $25 discount by using the code DAILYJS.

bower-registry

If you're looking to set up your own Bower registry, then take a look at bower-registry (GitHub: neoziro / bower-registry, License: MIT, npm: bower-registry) by Greg Bergé. This is an Express web application that stores data in Redis, but the author notes it could be easily adapted to support other databases like MongoDB and PostgreSQL.

Running bower-registry -d redis on the command-line will start a server. Other options can be viewed by typing bower-registry -h. The app can also be loaded as a Node module, and require('bower-registry').Registry is the Express app instance.

Helmsman

Helmsman (GitHub: mattmcmanus / node-helmsman, License: MIT, npm: helmsman) by Matt McManus is an opinionated command-line application development kit. The interface style is based on Git's subcommands:

A common setup for command line applications is <command> <subcommand> <arguments/options> (for example: git commit -m 'message'). Rather than having a giant file that switches or if elses over each potential subcommand, it's much neater to store each subcommand in it's own file (bin/command,bin/command-subcomand, bin/command-subcommand2, etc). Doing this however introduces some annoying manual steps which helmsman hopes to solve.

The subcommand-style API is based on metadata exposed through exports. If the file is run directly rather than loaded with require, then your script should run as it would normally:

#!/usr/bin/env node

// 1. To expose the metadata simply `exports.command`
exports.command = {  
  description: 'Show current worker counts and their pids'
};

// 2. Then make sure it only runs when it's directly called:
if (require.main === module) {  
  // Parse options and run the magic
}