Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS console SyntaxError: Unexpected token * for generator

I am running the NodeJS console:

$ node --version
v0.12.0

And I am trying to implement a Generator function such as this one

function* colorGen() {
    var colors = ["red", "green", "blue", "white"]
    var i = 0;
    yield colors[i];
    i += 1;
    if (i > 3) {i = 0;}  
}

But when I run the first line, I get a syntax error:

$ node
> function* colorGen() {
SyntaxError: Unexpected token *
    at Object.exports.createScript (vm.js:44:10)
    at REPLServer.defaultEval (repl.js:117:23)
    at bound (domain.js:254:14)
    at REPLServer.runBound [as eval] (domain.js:267:12)
    at REPLServer.<anonymous> (repl.js:279:12)
    at REPLServer.emit (events.js:107:17)
    at REPLServer.Interface._onLine (readline.js:214:10)
    at REPLServer.Interface._line (readline.js:553:8)
    at REPLServer.Interface._ttyWrite (readline.js:830:14)
    at ReadStream.onkeypress (readline.js:109:10)
> 

Why is this happening?

like image 650
ApathyBear Avatar asked May 25 '15 18:05

ApathyBear


2 Answers

Generator functions are currently available in node behind a flag --harmony_generators. See Features Implemented in V8 and Available in Node.

like image 77
Bartosz Gościński Avatar answered Nov 09 '22 03:11

Bartosz Gościński


Functions with asterisk are in ECMAScript 6 syntax.

function* name() 

I think your nodejs can't recognize it. Use --harmony flag, when you start your server.

like image 4
Kristiyan Avatar answered Nov 09 '22 04:11

Kristiyan