使用node.js和handlebars.js显示文件夹

时间:2014-01-01 21:31:03

标签: node.js handlebars.js eventemitter

我想显示我在某个目录下的文件夹, 我正在使用express3-Handlebars。 HTML代码:

{{gallery}}

这里有我的:

res.render('pages/gallery', {
        title: 'גלריה',
        HomeActive:'',
        ContactActive:'',
        AboutActive:'',
        GalleryActive:'active',
        MapActive:'',
        EmailActive:'',
        helpers:{
            gallery:function(){
                var albums = [],
                    albumDir = './public/img/albums';
                eventEmitter.on('readFolder',function(){
                    var albums = [];
                    fs.readdir(albumDir, function (err, files) {
                        if (err) console.log(err);

                        for (var i = 0; i < files.length; i++) {

                            if (files[i].indexOf('.') == -1)
                                albums.push({album: files[i]});
                        }
                        console.log("read " + files);
                        eventEmitter.emit('folderRead',files);
                    });
                });
                console.log(albums);
                eventEmitter.emit('readFolder');
                return eventEmitter.on('folderRead',function(files){
                    console.log("end " + files)
                    return files;
                });
            }
        },
        PagitionHide:'hide'
    });

我在没有eventEmitters的情况下设置相册时遇到了问题,看起来似乎在做:

gallery:function(){
    var albums = [],
            albumDir = './public/img/albums';

            fs.readdir(albumDir, function (err, files) {
                if (err) console.log(err);

                for (var i = 0; i < files.length; i++) {

                    if (files[i].indexOf('.') == -1)
                        albums.push({album: files[i]});
                }

                console.log(albums); //logs the folders names.
            });
console.log(albums); //logs an empty array
return albums;
}

导致相册为空,我猜想是node.js的异步。

但现在当HTML呈现它的显示和对象时如下:[object Object] 我在这做错了什么?

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

{{#each gallery}}
    {{album}}
{{/each}}