nodejs如何动态读取文件夹下图片,并放入json数据中并显示

var fs=require('fs');
1、存储格式为:
{'01.jpg': './public/images/01.jpg' , '11.jpg':'./public/images/11.jpg' }
function read_directory(path, next) {
    fs.readdir("./public/images/", function (err, files) {
        var count = files.length,
            results = {};
        files.forEach(function (filename) {
            fs.readFile(filename, function (data) {
                results[filename] = "./public/images/"+filename;
                count--;
                if (count <= 0) {
                    next( results );
                }
            });
        });
    });
}

function read_directories(name, next) {
    var count = name.length,
        data = {};
    name.forEach(function (path) {
        read_directory(path, function (results) {
            data[path] = results;
            count--;
            if (count <= 0) {
                next(data);
            }
        });
    });
}

read_directories(['name','name2','name3'] ,function (data) {//其中name=name2=name3
    var fileName=data.name;
    var fileNum = 0;
    for(var key in fileName)
    {
        if(fileName.hasOwnProperty(key)){
            fileNum++;}
    }
//    console.log(fileNum);
//    console.log(fileName);
    for(var i in fileName){
        console.log("the image name is:{"+ i +"} and the path is:{"+fileName[i]+"}");
    }
});
2、把读取的文件信息存储为令一种形式:
[ {imageName: '11.jpg', imagePath: './public/images/11.jpg' },
  { imageName: '01.jpg', imagePath:'./public/images/01.jpg' } ]
 
fs.readdir("./public/images/", function (err, files) {//读取文件夹下文件
    var count = files.length,
        results =new Array() ;
    files.forEach(function (filename) {
        fs.readFile(filename, function (data) {
            var tmpResult={};
            tmpResult["imageName"]=filename;
            tmpResult["imagePath"] = "./public/images/"+filename;
            results[count-1]=tmpResult ;
            count--;
            if (count <= 0) {
                console.log(results);
                console.log(results[1].imageName);
            }
        });
    });
});

你可能感兴趣的:(nodejs如何动态读取文件夹下图片,并放入json数据中并显示)