I have a directory with files that I need to parse and save in an array of JavaScript objects. In the constructor, as soon as I reach point 2 in the code below, this
becomes undefined
and in point 3 I don't have access to this.data
. What's the best way to fix the code and achieve the goal?
function Service(path) {
this.data = [];
console.log(this); // point 1
fs.readdir(path, function (err, files) {
console.log(this); // point 2
files.forEach(function (file) {
fs.readFile(path + file, function (err, data) {
parseString(data, function (err, result) {
this.data.push(result); // point 3
});
});
}, this);
});
}
Service.prototype.getData = function () {
// do something with `this.data` and return the result
};
I tried saving this
as self
, but in the end self
ends up with proper array, while this
does not:
function Service(path) {
var self = this;
this.data = [];
fs.readdir(path, function (err, files) {
files.forEach(function (file) {
fs.readFile(path + file, function (err, data) {
parseString(data, function (err, result) {
self.data.push(result);
});
});
});
});
setTimeout(function () {
console.log(this); \\ point x
console.log(self); \\ point y
}, 3000);
}
Service.prototype.getData = function () {
// do something with `this.data` and return the result
};