0

So the code I have written is below and the console log of the posts should be the same since the variable is global but the output is different. The '1' in the initialization is just a dummy just don't think about it. The output in the terminal is 1 (from the initialization) followed by= the first object logged by the first console log since it's a promise. But I would want the global posts to store the value of parsed JSON from the data so that I can use the variable in other functions in the same module. Am I doing something wrong?

const fs = require("fs"); 

var posts = [1];
var categories = [];

module.exports.initialize = function() {
    return new Promise((res, rej) => {
        // used to load the views.json file
        fs.readFile('data/posts.json', 'utf8', (err, data) => {
            if (err) {
                rej(err + 'Cannot read posts.json');
            } else {
                try{
                    posts = JSON.parse(data);
                    //console.log(posts)
                } catch (err) {
                    rej(err + 'Cannot Parse posts.json');
                }
            }
            **console.log(posts[0])**
        });
        **console.log(posts[0])**
        // used to load the categories.json file
        fs.readFile('data/categories.json', 'utf8', (err, data) => {
            if (err) {
                rej(err + 'Cannot read categories.json');
            } else {
                try{
                    categories = JSON.parse(data);
                } catch (err) {
                    rej(err + 'Cannot parse categories.json');
                }
            }
        });

        // if the files were read successfully
        res();
    });

I wanted the global variable called posts to store the value from JSON.parse but it seems the value is stored not in the global scope but in the block scope, I guess this is happening with the other global variable as well.

Krins
  • 11
  • 3

0 Answers0