Using Nodejs ES6 generators today example
You can setup a flexible system using ES6 generators for Node even today
EcmaScript6 (called Harmony) has an excellent feature - generators. They offer a very intuitive way of dealing with asynchronous code (usually in conjunction with promise library like Q). Once I wrapped my mind around using them, I wanted to simplify my projects (typically using promises) using generators.
After looking around, I found that generators are supported pretty much by every tool I use. The only thing stopping me is a requirement to share my module with others, who are still running stable Nodejs 0.10.x without generator support.
I write all my code as usual, but using EcmaScript6 in folder
I run the code using node v0.11 with
--harmony command line option, by using
harm=node --harmony. I am also using
grunt-regenerator to convert
every file from ES6 to EcmaScript5 (using regenerator).
// Gruntfile.jsregenerator:all:files:expand: truecwd: 'es6/'src: '**/*.js'dest: 'es5/'
The generated EcmaScript5 code is committed to the repo too.
I point at a simple pick-ecmascript.js file from package.json that select which code to run: ES6 or ES5. The script looks at the node version and command line arguments to figure out which version to start. If ES5 is selected, the script also loads a small supporting function by needed to run the converted code (provided by the regenerator)
if processversionsnodesplit'.'1 < 11return false;return processexecArgvsomereturn arg == '--harmony';;if isHarmonyconsole.log'Harmony!';require'./es6';elseconsole.log'ES5 :(';require'./node_modules/grunt-regenerator/node_modules/regenerator/runtime/dev.js';require'./es5';
A typical run using node v0.11 using
npm start command
$ npm start> firstname.lastname@example.org start /Users/gbahmutov/git/es6-generators-example> node --harmony pick-ecmascript.jsHarmony!1249
Author: Gleb Bahmutov © 2013
License: MIT - do anything with the code, but don't blame me if it does not work.
Support: if you find any problems with this module, email / tweet / open issue on Github