user2036108
user2036108

Reputation: 1307

Global Scope not working?

I'm currently trying to add the data from each JSON file in a specific folder to a string and then log that string to the console - but it's not working. Is anyone able to shed some light on where I'm going wrong?

global.article = "";
for(i=0;i<posts.length;i++){
  fs.readFile('posts/' + posts[i], 'utf8', function(err, json){
    var post = JSON.parse(json);
    article += "<article>";
    article += "<blockquote>";
    article += "<h3>" + post.title + "</h3>";
    article += "<small>" + post.date + "</small>";
    article += post.content;
    article += "</blockquote>";
    article += "</article>";
  });
}
console.log(article);

Upvotes: 1

Views: 64

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

fs.readFile is asynchronous, so the console.log(article); at the bottom is going to run before any of your fs.readFile callbacks with the JSON processing that populates article.

Take a look at using the async library to provide asynchronous flow control, but a simple solution that illustrates that nature of the problem is to keep track of the callback count and only process article once they've all completed:

global.article = "";
var count = 0;
for(i=0;i<posts.length;i++){
    fs.readFile('posts/' + posts[i], 'utf8', function(err, json){
        var post = JSON.parse(json);
        article += "<article>";
        article += "<blockquote>";
        article += "<h3>" + post.title + "</h3>";
        article += "<small>" + post.date + "</small>";
        article += post.content;
        article += "</blockquote>";
        article += "</article>";
        if (++count === posts.length) {
            // All callbacks are now complete.
            console.log(article);
        }
   });
}

Upvotes: 1

Jack Gardner
Jack Gardner

Reputation: 341

Instead of 'global.article', you should instead declare a new variable for the article.

var article = "";

If you need to update global.article when you have finished constructing the string in the loop, you can assign back to it when the loop exits.

global.article = article;

If for some reason you want to update global.article directly, you can update global.article instead, as shown in this JSFiddle:

http://jsfiddle.net/Lkpe4/

HTH

Upvotes: 1

Related Questions