Ricky
Ricky

Reputation: 3072

Angular + NodeJS: Read Files From Folder With Promises (fs.fileRead and fs.readdir)

I'm trying to read files from a folder using NodeJS and Angular. I'm able to iterate through the folder and access the files data, no problems here. My main issue i that i'm unable to pass the result (array of names) to the $scope and show it to the user - the array is always empty. I think this is related with fs asynchronous behaviour.

I'm doing the following:

Angular Service:

myApp.service('peopleService', ['$q', '$http', function($q, $http) {

    var self = this;
    this.people = [];

    var peopleService = new Promise(function(resolve, reject) {
        fs.readdir(folderPath, function(err, files) {
            files.forEach(function(file) {
                var obj;
                fs.readFile(filePath, 'utf8', function (err, data) {
                    obj = JSON.parse(data);

                    var person = { name: obj.obituary.name, ... };

                    self.people.push(person);
                });
            });
        });

        resolve(self.people);
    }).then(function(people) {
        return people;
    });

    return peopleService;
}]);

Angular Controller:

myApp.controller('homeController', ['$scope', '$http', 'peopleService', function($scope, $http, peopleService) {

    $scope.people = [];

    peopleService.then(function(people) {
        $scope.people = people;
        console.log($scope.people); //empty array (Array[0])
    });

}]);

Angular Page:

<div class="list-group">
    <a href="#" class="list-group-item" ng-repeat="person in people">
        {{person.name}}
    </a>
</div>

What am i doing wrong?

Upvotes: 0

Views: 1535

Answers (1)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37373

Why you'are mixing nodeJS code with angularJS code?

the problem is resolve(self.people) is executed before readdir and readFile callbacks are executed because they are asynchronous, so you have to make sure that resolve(self.people) will executed after readdir and readFile callbacks :

new Promise(function(resolve, reject) {
        fs.readdir(folderPath, function(err, files) {
            var count = 0;
            files.forEach(function(file) {
                var obj;
                fs.readFile(filePath, 'utf8', function (err, data) {
                    obj = JSON.parse(data);

                    var person = { name: obj.obituary.name, ... };

                    self.people.push(person);

                    count++;
                    if(count === files.length){
                       resolve(self.people);
                    }
                });
            });
        });

    }).then(function(people) {
        return people;
    });

Upvotes: 1

Related Questions