Node.js: for each … in not working

249,940

Solution 1

Unfortunately node does not support for each ... in, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.

You'll have to settle for array.forEach(function(item) { /* etc etc */ }).

EDIT: From Google's official V8 website:

V8 implements ECMAScript as specified in ECMA-262.

On the same MDN website where it says that for each ...in is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.

Solution 2

for (var i in conf) {
  val = conf[i];
  console.log(val.path);
}

Solution 3

https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.

Solution 4

There's no for each in in the version of ECMAScript supported by Node.js, only supported by firefox currently.

The important thing to note is that JavaScript versions are only relevant to Gecko (Firefox's engine) and Rhino (which is always a few versions behind). Node uses V8 which follows ECMAScript specifications

Solution 5

This might be an old qustion, but just to keep things updated, there is a forEach method in javascript that works with NodeJS. Here's the link from the docs. And an example:

     count = countElements.length;
        if (count > 0) {
            countElements.forEach(function(countElement){
                console.log(countElement);
            });
        }
Share:
249,940
pvorb
Author by

pvorb

Updated on July 08, 2020

Comments

  • pvorb
    pvorb almost 4 years

    I wanted to use for each ... in with Node.js (v0.4.11).

    I use it like this:

    var conf = {
       index: {
          path: {
             first: "index.html",
             pattern: "index/{num}.html"
          },
          template: "index.tpl",
          limit: 8
       },
       feed: {
          path: "feed.xml",
          template: "atom.tpl",
          limit: 8
       }
    }
    
    for each (var index in conf) {
      console.log(index.path);
    }
    

    I get the following error:

            for each (var index in conf) {
         ^^^^
    
    node.js:134
            throw e; // process.nextTick error, or 'error' event on first tick
            ^
    SyntaxError: Unexpected identifier
        at Module._compile (module.js:397:25)
        at Object..js (module.js:408:10)
        at Module.load (module.js:334:31)
        at Function._load (module.js:293:12)
        at require (module.js:346:19)
        at Object.<anonymous> (/home/paul/dev/indexing/lib/Index.js:3:13)
        at Module._compile (module.js:402:26)
        at Object..js (module.js:408:10)
        at Module.load (module.js:334:31)
        at Function._load (module.js:293:12)
    

    Where is the mistake? for each ... in is supported since Javascript 1.6.

    See MDN for information about the usage of for each ... in.