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?