當我們進行查找的時候,使用了迭代器
var fs = require("fs");
exports.getAllAlbums = function (callback) {
fs.readdir("./uploads",function (err,files) {
var allAllbums = [];
//迭代器 異步變同步
(function iterator(i) {
if( i == files.length){
console.log(allAllbums);
callback(allAllbums);
return;
}
fs.stat("./uploads/" + files[i],function (err,stats) {
if(stats.isDirectory()){
allAllbums.push(files[i])
}
iterator(i + 1);
});
})(0);
})
//找到所有文件夾
}
這裏是router.js
var file = require("../models/file")
exports.showIndex = function (req,res) {
//傳統思維,不適用noed
// res.render("index",{
// "albums": file.getAllAlbums()
// });
//這就是Node.js的編程思維,就是所有的東西,都是異步的
//所以,內層函數,不是return回來東西,而是高層函數提供的
//回調函數。把數據當做回調函數的參數來使用。
file.getAllAlbums(function (allAllalbums) {
res.render("index",{
"albums": allAllalbums
})
})
}
exports.showAlbum = function (req,res) {
res.send("相冊" + req.params.albumName);
}