-1

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"

Philipp Claßen
  • 32,622
  • 19
  • 125
  • 194
  • 1
    [It seems asterisk is needed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) – aarosil Feb 16 '15 at 21:59
  • I would advise against using generators because they are an [optimization killer](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#2-unsupported-syntax). Perhaps you should use a [CPS compiler](http://chumsley.org/jwacs/) instead. – Aadit M Shah Feb 17 '15 at 02:37
  • I'm confused by this question--any beginner tutorial on generators would tell you that you need the `*`, and that in node you need the `--harmony` option. Granted the error message might be a little less obtuse. –  Feb 17 '15 at 03:07
  • @torazaburo Well, I copied the code from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators. Have to be more careful the next time. – Philipp Claßen Feb 17 '15 at 09:34
  • Might want to pay more attention to big red bold warnings at the top of the page that say "The content of this page is very outdated and Firefox-specific". –  Feb 17 '15 at 10:03

1 Answers1

4

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;
}
Community
  • 1
  • 1
Mike Atkins
  • 1,431
  • 11
  • 10