es6-generators-example
v0.0.1
Published
Using Nodejs ES6 generators today example
Downloads
8
Readme
ES6-generators-example
You can setup a flexible system using ES6 generators for Node even today
Background
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.
Solution
I write all my code as usual, but using EcmaScript6 in folder es6
.
I run the code using node v0.11 with --harmony
command line option, by using
an alias harm=node --harmony
. I am also using
grunt-regenerator to convert
every file from ES6 to EcmaScript5 (using regenerator).
// Gruntfile.js
regenerator: {
all: {
files: [{
expand: true,
cwd: 'es6/',
src: ['**/*.js'],
dest: 'es5/'
}]
}
}
The generated EcmaScript5 code is committed to the repo too.
runtime
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)
function isHarmony() {
if (process.versions.node.split('.')[1] < 11) {
return false;
}
return process.execArgv.some(function (arg) {
return arg == '--harmony';
});
}
if (isHarmony()) {
console.log('Harmony!');
require('./es6');
} else {
console.log('ES5 :(');
require('./node_modules/grunt-regenerator/node_modules/regenerator/runtime/dev.js');
require('./es5');
}
execution
A typical run using node v0.11 using npm start
command
$ npm start
> [email protected] start /Users/gbahmutov/git/es6-generators-example
> node --harmony pick-ecmascript.js
Harmony!
1
2
4
9
Small print
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