0

I have the following code:

"use strict";
const fs = require('fs');

class Foo {

    run() {
        this.files = [];
        fs.readdir(__dirname, (err, dir) => {
            for (let filePath of dir) {
                this.files.push(filePath); // dosent change this.files outside the anonymous function
            }
        });
        console.log(this.files);// outputs []
    }
}

let foo = new Foo();
foo.run();

I want it to output the list of files.

However it gives "[]" instead, indicating "this.files" did not change.

Note I am using Node and Typescript (but a JS solution will also do).

halfer
  • 19,824
  • 17
  • 99
  • 186
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
  • Just move the `console.log` *into* the callback. – T.J. Crowder Jun 30 '16 at 05:46
  • 1
    BTW, that's not TypeScript. It's just JavaScript (specifically ES2015+). – T.J. Crowder Jun 30 '16 at 05:46
  • But that's not what I want. I want to retrieve the files variable and get it out of the anonymous function. This is just a small example to illustrate the problem. I am also unsure how that question solves the problem – Yahya Uddin Jun 30 '16 at 05:48
  • What does *"I want to retrieve the files variable and get it out of the anonymous function"* mean? If you mean you want `run` to `return xxx`, it can't. If you just want to pass the list to code outside of `run`, then you give `run` a callback and call it (or use promises), as the linked question's answers explain. – T.J. Crowder Jun 30 '16 at 05:52
  • Sorry let me clarify. Basically the changes I made to this.files in the anonymous function should be the same this.files outside the anonymous function. I'll change the question to make it easier to understand. – Yahya Uddin Jun 30 '16 at 05:54
  • That's how I read the question. The linked question's answers answer that. – T.J. Crowder Jun 30 '16 at 05:57
  • 1
    *"dosent change this.files outside the anonymous function"* Yes, it does. It just doesn't change it until **later**, after `run` has returned. – T.J. Crowder Jun 30 '16 at 05:58
  • Oh didn't know that. I'll look at this again – Yahya Uddin Jun 30 '16 at 06:00

0 Answers0