Search code examples
javascriptnode.jsgeneratorv8ecmascript-harmony

Is it possible to use generators in node v0.12.0?


I thought node v0.12.0 would support generators but I cannot get it to work. Unfortunately, I haven't found any clear statements whether generator are supported or not.

This is what I tried:

# example.js
"use strict";

function simpleGenerator(){
  yield "first";
  yield "second";
  yield "third";
  for (var i = 0; i < 3; i++)
    yield i;
}

Execution fails as the yield keyword is not supported:

$ node --version`
v0.12.0

$ node example.js 
/tmp/example.js:4
  yield "first";
  ^^^^^
SyntaxError: Unexpected strict mode reserved word
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Setting the --harmony flag does not work either:

$ node --harmony example.js
   ... the identical error ...

Leaving out "use strict" also fails. It only leads to another error message: "Unexpected string"


Solution

  • As noted by aarosil, an asterisk is needed.. and you need the --harmony flag. Also, see this question for ES6 features supported in 0.12.0: ECMAScript 6 features available in Node.js 0.12

    "use strict";
    
    function* simpleGenerator(){
      yield "first";
      yield "second";
      yield "third";
      for (var i = 0; i < 3; i++)
        yield i;
    }