Question

I would like to populate a list of object from a file using the fs.readFile method using the this keyword of my JavaScript class

var MyReaderClass = (function() {
    //Const    

    function MyReaderClass() {
        this.readObjects = [];

        /**    
         * Default constructor for the MyReaderClass class
         */
        var _constructor = function() {

        }

        _constructor.call(this);
    }

    //Public    
    MyReaderClass.prototype.ReadFiles = function(p_path) {
        var files = fs.readdirSync(p_path);

        for (var i in files) {
            var fileName = files[i];
            fs.readFile(path.join(p_path, fileName), 'utf8', function(err, data) {
                if (err) {
                    return console.log(err);
                } 
                else {
                    var formattedData = /*... Logic to format my data into an object*/;
                    this.readObject.push(formattedData); //The "this" is not the reference to my class.
                }
            });
        }
    }
    return MyReaderClass;
})();

Even if I'm creating a local instance (_self, that, instance, etc.) of my this variable, outside the readFile method, my local instance won't be filled up.

Any idea how I could accomplish this ?

Was it helpful?

Solution

readFile is async method and you lose your execute context. You need bind your class to readFile callback as a context. Use Function.prototype.bind:

MyReaderClass.prototype.ReadFiles = function(p_path) {
    var files = fs.readdirSync(p_path);
    for (var i in files) {
        var fileName = files[i];
        fs.readFile(path.join(p_path, fileName), 'utf8', function(err, data) {
            /*readFile callback*/
        }.bind(this));//also here was a syntax error
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top