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.

5
  • What does readFiles do? Is it asynchronous? It looks like it. Commented Sep 29, 2016 at 16:33
  • readFiles is asynchronous process. so please readFileSync Commented Sep 29, 2016 at 16:37
  • Since it is closed I can only refer you to my other answers that explain how things like that work: 1, 2, 3, 4 Commented Sep 29, 2016 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. Commented Sep 29, 2016 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. Commented Sep 29, 2016 at 16:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.