0

I have a function that calls the readFiles function, and parses the data into data{}, but once outside the loop, data == {}, and that is not what I am trying to achieve. Any pointers of where I should be looking?

    data = {};
    readFiles({
        dirname: path.join(__dirname, '../ping/'), onFileContent: (filename, content) => {
            data[filename] = content;
            console.log(data);
        }, onError: function (error) {
           console.log(error);
        }
    });
    console.log(data);

As I stated, the console.log(data) at the end has {} as it's value.

Here is readFile

function readFiles(parameters) {
    var dirname = parameters.dirname;
    var onFileContent = parameters.onFileContent;
    var onError = parameters.onError;
    fs.readdir(dirname, (err, filenames)=>{
        if (err) {
            onError(err);
            return;
        }
        filenames.forEach(filename => {
            return fs.readFile(path.resolve(dirname, filename), 'utf-8', (err, content)=>{
                if (err) {
                    onError(err);
                    return;
                }
                onFileContent(filename, content);
            });
        });
    });
}

If I change the second block to use readFileSync, I get errors that I have no idea how to correct.

  • What does `readFiles` do? Is it asynchronous? It looks like it. – puelo Sep 29 '16 at 16:33
  • readFiles is asynchronous process. so please readFileSync – Satish Kumar sonker Sep 29 '16 at 16:37
  • Since it is closed I can only refer you to my other answers that explain how things like that work: [1](http://stackoverflow.com/questions/39659829/how-can-i-chain-these-functions-together-with-promises/39660257#39660257), [2](http://stackoverflow.com/questions/39691647/nodejs-express-and-promises-not-doing-what-i-expect/39691872#39691872), [3](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success/5316805#5316805), [4](http://stackoverflow.com/questions/39764599/how-can-i-return-status-inside-the-promise/39765591#39765591) – rsp Sep 29 '16 at 16:38
  • When I change over to readFileSync, I have the same effect, but even logging the array in the loop no longer outputs data. – David Null Sep 29 '16 at 16:39
  • @DavidNull This is exactly how Node works, or any other asynchronous environment. You have to keep it in mind and try to see what happens in what order to understand how the program should behave. I was writing an answer with numbered lines of the order of execution of your program but the question got closed before I finished writing so I couldn't post it. – rsp Sep 29 '16 at 16:45

0 Answers0