是否可以在节点 v0.12.0 中使用生成器?

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

我认为节点 v0.12.0 会支持生成器,但我无法让它工作。不幸的是,我没有找到任何明确的声明是否支持生成器。

这是我试过的:

# example.js
"use strict";

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

执行失败,因为 yield 关键字不受支持:

$ 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

设置 --harmony 标志也不起作用:

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

省略 "use strict" 也会失败。它只会导致另一条错误消息:"Unexpected string"

aarosil, an asterisk is needed.. and you need the --harmony flag. Also, see this question for ES6 features supported in 0.12.0:

所述
"use strict";

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