1

I have this simple code:

File app.js:

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');

var downloader = require('./routers/downloader.js');

const app = express();

downloadAll();

function downloadAll() {
    downloader.test();
}

File downloader.js:

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');
var methods = {};

methods.test = function(req, res) {
    for(var i = 1; 10; i++) {
        console.log(i); // DOESN'T WORK
    }

    var obj;
    fs.readFile('./output/ita-2015-24m.json', 'utf8', function(err, data) {
        if(err) {
            throw err;
        }
        obj = JSON.parse(data);
        console.log(obj); 
    }
}

module.exports = methods;

When I run app.js using node app.js, I get: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, .... The loop doesn't end.

I try to change position to this loop, interting it inside readFile function but it's the same problem.

My goal is iterate throug obj object.

Why? How can I solve?

1
  • Your var methods = {}; is a variable that hold the value of an empty object. You should use a for in loop (watch out for non-enumerable properties) instead of testing your code with a for loop Commented Mar 7, 2018 at 14:46

4 Answers 4

6

When I run app.js using node app.js, I get: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, .... The loop doesn't end.

Your loop doesn't have end-condition, hence it will keep on incrementing i

Make it

for(var i = 1; i <= 10; i++) {
    console.log(i); // DOESN'T WORK
}
Sign up to request clarification or add additional context in comments.

Comments

1

You've written for(var i = 1; 10; i++)

The loop will never end because 10 is always true (or at least never false). Should be something like:

for(var i = 1; i<10; i++)

Comments

0

Instead of:

for(var i = 1; 10; i++)

Try:

for(var i = 1; i <= 10; i++) 

Comments

0

if you want 10 elements you can use

for(var i = 1; i<= 10; i++)

or

for(var i = 0; i< 10; i++)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.