从node.js + express4 写一个自己的博客网站教程中写代码,发现获取所有文件夹下的文件,最终结果如何在外面得到呢??return 返回的不是getBlogList的返回值吧?
js
function getBlogList(blogDir) { fs.readdir(blogDir, function (err, files) { var blogList = []; if (files && files.length) { files.forEach(function (filename) { //split file name and generate url... //... //create a blogItem { title: blogTitle, url: blogUrl } blogList.push(blogItem); }); } return blogList; }); }
刚接触node,疑惑很久,请各位赐教~谢谢
怪我咯2017-04-17 11:30:04
You can choose from the following methods. The first is the most traditional, the fourth is the most elegant (but can’t be used now), and the third is second only to the fourth in elegance. The method during the transition period, The second one is more widely used and comes in many variations.
//经典的callback写法
function getBlogList(blogDir,callback) {
fs.readdir(blogDir, function (err, files) {
if(err){
callback(err);
return;
}
var blogList = [];
if (files && files.length) {
files.forEach(function (filename) {
//split file name and generate url...
//...
//create a blogItem { title: blogTitle, url: blogUrl }
blogList.push(blogItem);
});
}
callback(null,blogList);
});
}
// 使用方法
getBlogList("/",function(err, blogList){
//这里就可以用 blogList
})
javascript
// 第二种写法,Promise function getBlogList(blogDir) { return new Promise(function(resolve,reject){ fs.readdir(blogDir, function (err, files) { if(err) reject(err); var blogList = []; if (files && files.length) { files.forEach(function (filename) { //split file name and generate url... //... //create a blogItem { title: blogTitle, url: blogUrl } blogList.push(blogItem); }); } resolve(blogList); }); }) } // 使用方法 var bloglistP= getBlogList("/"); bloglistP.then(function(blogList){ //这里就可以用 blogList })
javascript
// 第三种写法,生成器yield模式,需要co或者koa来配合,需要node>=0.11.0 var co=require("co"),thunkify=require("thunkify"); var readdir= thunkify(fs.readdir); function* getBlogList(blogDir) { var files= yield readdir(blogDir); var blogList = []; if (files && files.length) { files.forEach(function (filename) { //split file name and generate url... //... //create a blogItem { title: blogTitle, url: blogUrl } blogList.push(blogItem); }); } return blogList; } //使用方法 co(function*(){ //这里就可以用 blogList var blogList=yield getBlogList("/"); })()
javascript
// ES7的async/await模式,目前node不支持,只是演示 async function getBlogList(blogDir) { var files= await fs.readdir(blogDir); var blogList = []; if (files && files.length) { files.forEach(function (filename) { //split file name and generate url... //... //create a blogItem { title: blogTitle, url: blogUrl } blogList.push(blogItem); }); } return blogList; } // 使用方法 // 这里就可以用 blogList var blogList=await getBlogList("/");
PHP中文网2017-04-17 11:30:04
The one upstairs is the correct answer. Add a simple and crude method
var fs = require('fs')
function getBlogList(blogDir) {
return fs.readdirSync(blogDir)
}
var files = getBlogList('/');
console.log(files)