Search code examples
javascriptnode.jsecmascript-harmony

Run a node shell script in --harmony mode


How can I run a globally-installed node module that exposes a shell script in --harmony mode?


Solution

  • TL;DR: Just use Node 5+, most ES6 features will be availble right away.


    2016 answer

    This is more like an amendment to the 2015 answer.
    The reason is because Node.js and io.js have converged, and the project is now a lot stronger, having lots of updates while keeping Long-Term Support (LTS) and supporting lots of ES6 features, in addition to those that io.js did support as well.

    Notable features available in Node.js 5.0.0+:


    2015 answer

    We now have io.js available. It's reliable, fast, and up-to-date with the stable ES6 specs.

    Depending on what ES6 features you want, you can use it with no flag at all. From their website:

    • Block scoping
      • let
      • const
      • function-in-blocks

        As of v8 3.31.74.1, block-scoped declarations are intentionally implemented with a non-compliant limitation to strict mode code. Developers should be aware that this will change as v8 continues towards ES6 specification compliance.

    • Collections
      • Map
      • WeakMap
      • Set
      • WeakSet
      • Generators
    • Binary and Octal literals
    • Promises
    • New String methods
    • Symbols
    • Template strings

    2014 answer

    What about spawning a second Node process with your stuff?

    #!/usr/bin/env node
    
    var spawn = require("child_process").spawn;
    var child = spawn(process.execPath, [ "--harmony", "yourscript.js" ], {
      cwd: __dirname
    });
    
    child.stdout.on("data", function( data ) {
      console.log(data);
    });
    
    child.stderr.on("data", function( data ) {
      console.error(data);
    });
    

    EDIT: I believe process.execPath returns the node path, not the global script path in this case.
    However, you can always change it to node directly, but that could break installations without node in the PATH.