Angular + NodeJS:从带有Promises的文件夹中读取文件(fs.fileRead和fs.readdir)

时间:2017-03-04 23:31:54

标签: javascript angularjs node.js angular-promise fs

我正在尝试使用NodeJS和Angular从文件夹中读取文件。我能够遍历文件夹并访问文件数据,这里没有问题。 我的主要问题是我无法将结果(名称数组)传递给$ scope并将其显示给用户 - 数组始终为空。我认为这与fs异步行为有关。

我正在做以下事情:

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;
}]);

角度控制器:

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>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

为什么你要将nodeJS代码与angularJS代码混合使用?

问题是resolve(self.people)在执行readdirreadFile回调之前执行,因为它们是异步的,因此您必须确保resolve(self.people)将在{readdir之后执行1}}和readFile回调:

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;
    });