The JavaScript blog.


cli node modules npm

Trash: Cross-Platform Delete

Posted on .


Trash (GitHub: sindresorhus / trash, License: MIT, npm: trash) is a cross-platform command-line tool for safely deleting files.

Although those of us who are raised on Linux find the indignity of a Trash folder or Recycle Bin annoying, it can be a useful safety net. It has support for Windows, OS X, and Linux:

function win(paths, cb) {  
  execFile('./Recycle.exe', ['-f'].concat(paths), {
    cwd: path.join(__dirname, 'vendor', 'cmdutils')
  }, function (err) {

The Linux version has a small script that wraps around trash-cli:

function linux(paths, cb) {  
  execFile('./trash-put', paths, {
    cwd: path.join(__dirname, 'vendor')
  }, function (err) {
    if (err && /cannot trash non existent/.test(err.message)) {
      return cb(new Error('Item doesn\'t exist'));


The test is written as an integration test, so it uses Node's fs module to create and move files:

it('should trash files', function (cb) {  
  fs.writeFileSync('fixture', '');
  fs.writeFileSync('fixture2', '');
  fs.writeFileSync('weird\\\\name\\"\'', '');

  ], function (err) {
    assert(!err, err);


events cli node modules pubsub

Node Roundup: 0.11.2, 0.10.6, subscribe, Omelette

Posted on .

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

Node 0.11.2 and 0.10.6

Clearly the Node core developers have had an early summer holiday, and are now back to unleash new releases. In the space of a few days 0.11.2 and 0.10.6 were released. I was intrigued by the Readable.prototype.wrap update, which makes it support objectMode for streams that emit objects rather than strings or other data.

The 0.11.2 release has an update that guarantees the order of 'finish' events, and another that adds some new methods: cork and uncork. Corking basically forces buffering of all writes -- data will be flushed when uncork is called or when end is called.

There is a detailed discussion about cork and the related _writev method on the Node Google Group: Streams writev API. There are some interesting comments about a similar earlier implementation by Ryan Dahl, the validity of which Isaac questions due to Node's code changing significantly since then.

If you want to read about writev, check out the write(2) (man 2 write) manual page:

Write() attempts to write nbyte of data to the object referenced by the descriptor fildes from the buffer pointed to by buf. Writev() performs the same action, but gathers the output data from the iovcnt buffers specified by the members of the iov array...


Azer Koçulu has been working on a suite of modules for subscribing and observing to changes on objects:

Now he's also released a module for subscribing to multiple pub/sub objects:

var subscribe = require('subscribe');  
var a = pubsub();  
var b = pubsub();  
var c = pubsub();

subscribe(a, b, c, function(updates) {  
  // => a.onUpdate
  // => 3, 4
  // => c.onUpdate
  // => 5, 6

a.publish(3, 4);  
c.publish(5, 6);  

This brings a compositional style of working to Azer's other modules, allowing subscriptions to multiple lists and objects at the same time. The next example uses subscribe to combine the new-list module with new-object:

var fruits = newList('apple', 'banana', 'grapes');  
var people = newObject({ smith: 21, joe: 23 });

subscribe(fruits, people, function(updates) {  
  // => melon

  // => { alex: 25 }

people('alex', '25');  


Omelette (GitHub: f / omelette, License: MIT, npm: omelette) by Fatih Kadir Akın is a template-based autocompletion module.

Programs and their arguments are defined using an event-based completion API, and then they can generate the zsh or Bash completion rules. There's an animated gif in the readme that illustrates how it works in practice.


JSON cli node modules search unix sandbox

Node Roundup: 0.8.17, 0.9.6, gelf-node, jsong, Stuff.js

Posted on .

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

Node 0.8.17, 0.9.6 (Unstable)

Node 0.8.17 was released last week with a security fix for TypedArrays, so you should upgrade if you're using them:

If user input can affect the size parameter in a TypedArray, an integer overflow vulnerability could allow an attacker to write to areas of memory outside the intended buffer.

The unstable branch also saw a new release with 0.9.6. The streams API has changed slightly again as it continues to be developed: Isaac Schlueter added the readable.push method, and there are also fixes for TypedArrays in this branch too.


I've had a lot of luck with ElasticSearch. The last time I used it was on a project that used Node HTTP crawlers to index thousands of sites, and it was all backed by ElasticSearch. It worked extremely well and I actually got paid! If you're also using ElasticSearch, then you might be interested in the gelf-node module (GitHub: robertkowalski / gelf-node, License: MIT, npm: gelf) by Robert Kowalski. It works with Graylog2, allowing messages to be sent from Node:

var Gelf = require('gelf');  
var gelf = new Gelf({  
  graylogPort: 12201,
  graylogHostname: '',
  connection: 'wan',
  maxChunkSizeWan: 1420,
  maxChunkSizeLan: 8154

// The readme has an example message
gelf.emit('gelf.log', message);  

Graylog2 itself is released under the GPL (version 3).


jsong (GitHub: textgoeshere / jsong, npm: jsong, License: MIT) by Dave Nolan is a CLI tool and module for filtering JSON. It's built with streamin and clarinet, and shows full paths to matches:

$ cat my.json | jsong -k 'z\wp'

foo.bar.zip: val1  
foo.bar.zap: val2  
quux.zip: val  

Because it's built using streams, it should handle large JSON files.


Here's another project by Amjad Masad from Codecademy: Stuff.js (GitHub: Codecademy / stuff.js, License: MIT) -- an easy way to run arbitrary HTML and JavaScript in an iframe. It uses node-static and uglify-js to create a sandbox for securely running user-contributed code.

There's an example in Amjad's blog post that shows how to use it:

stuff(secureIframeUrl, function (context) {  
  var html = CodeMirror.fromTextArea($('#html'), {
    onChange: reload
  , mode: 'text/html'
  var js = CodeMirror.fromTextArea($('#js'), {
    onChange: reload
  , mode: 'javascript'
  var css = CodeMirror.fromTextArea($('#css'), {
    onChange: reload
  , mode: 'css'

  var t = null;
  function reload () {
    t = setTimeout(function () {
      var code = '<!DOCTYPE html><html><head>';
      code += '<style>'  + css.getValue() + '</style>';
      code += '<body>' + html.getValue();
      code += '<script>' + js.getValue() + '</script>';
      code += '</body></html>';
    }, 50);


cli node apps modules express unix

Node Roundup: Uptime, mmmagic, nodeflix, opt

Posted on .

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


Uptime screenshot

Uptime (GitHub: fzaninotto / uptime, License: MIT, npm: node-uptime) by Francois Zaninotto is an Express app for remote server monitoring. It's built with Mongoose, Bootstrap, ejs, Socket.IO, and jQuery.

To use the app, a YAML configuration file must be created for the sites you want to monitor. It seems like JSON would have been a more natural choice, but it's pretty easy to get started and there are examples in the documentation.

I'm always looking for open source Express applications, so keep them coming!


mmmagic (License: MIT, npm: mmmagic) by Brian White is a Node addon for libmagic, as used by the file command. It's asynchronous, and can provide the MIME type for a file (as well as other metadata):

var mmm = require('mmmagic')  
  , Magic = mmm.Magic;

var magic = new Magic(mmm.MAGIC_MIME_TYPE);  
magic.detectFile('/usr/bin/env', function(err, result) {  
  if (err) throw err;

It's currently built with node-waf (rather than gyp), but the author has included a Windows binary.


Nodeflix (License: MIT, npm: nodeflix) by Johnathan Leppert is a Netflix API client:

n.get('/catalog/people', { term: 'DeNiro' }, function(data) {  

I've noticed quite a few Node media-related modules cropping up, and with the continually improving Windows support it seems like Node is becoming a strong platform for home theatre-related application development. Is there a Node XBMC alternative yet?


opt (License: New BSD License, npm: opt) by R. S. Doiel is an options parser that can also load configuration files. It can generate usage based on the supplied parameters, but has a slightly different API to the other option parsing modules I've looked at -- callbacks are tied to each option instead of working with a parsed set of options:

#!/usr/bin/env node
var opt = require('opt')  
  , args;

function test(param) {  
  if (param) {
    console.log('--test parameter:', param);
  } else {
    console.log('No parameter supplied to --test');

opt.setup('Simple test script.');  
opt.set(['-h', '--help'], opt.usage, 'Show help');  
opt.set(['-t', '--test'], test, 'Run test');


This is quite different to how Commander.js works, for example.


libraries cli node

Krasota.js, Drink, Limit.js

Posted on .


Krasota.js (GitHub: veged / krasota.js, npm: krasota) by Sergey Berezhnoy is a modular source beautifier that uses grammars written with a fork of OMeta. It can force semicolons, join or split var statements, or even remove trailing whitespace.

It can be used as a Node module, or as a command-line utility:

$ krasota -i tests/join-vars.js -b krasota/lib/beautifiers/trailing-whitespaces -b krasota/lib/beautifiers/join-vars

Custom beautifiers can also be called from the command-line by using the -b switch with a file name.


Drink (GitHub: Nijikokun / drink, License: AOL/MIT, npm: drink) by Nijiko Yonskai is a wrapper around process that helps write periodic console utilities. The API is themed around "coffee" -- not CoffeeScript, but the brewed bean beverage, which is confusing because the author's examples are written in CoffeeScript.

A session is started and potentially kept alive by passing drink a process object. Calling sip will pass data to stir without line breaks. Listeners for single character input can be added by calling onTap. The author suggests this could be used to keep any kind of session from dying, so it could be used with something like an IRC client.


Limit.js (GitHub: m-gagne / limit.js, License: MIT) by Marc Gagne is a reusable event debouncer. I've written similar code myself to sensibly handle certain client-side UI elements, and events like window resizing.

Marc's implementation works by extending Function.prototype. There's an example on jsFiddle that illustrates the usage: Limit.js demo.

$(document).bind('mousemove', function(e) {
}.debounce(150)); // debounce with a 150 millisecond limit

$(document).bind('mousemove', function(e) {
}.throttle(150)); // throttle with a 150 millisecond limit