NodeJS缓存文件夹遍历

  当前项目需要将缓存图片入库,本人打算采用Nodejs进行处理,一来是联系,二来是测试一下Nodejs做这种问题的效率。

  首先,是本人打算是做文件夹遍历的同时,完成提取图片和入库操作。但是,在操作中遇到一个问题,由于数据量太大(100W张图片),导致node报打开文件过多错误。想来想去没有太好的方法解决,也请各位看官能提供一些好的建议。

  最后,测试了另外一种遍历方法,堆栈式。

  1.将数据路径遍历到数组中

function walk(path) {
    var dirList = fs.readdirSync(path);
    dirList.forEach(function(item) {
        if (fs.statSync(path + '/' + item).isDirectory()) {
            walk(path + '/' + item)
        } else {
            if (item.split(format)[1] == '') {
                putPathToList(path + '/' + item)
            }
        }
    })
}
function putPathToList(path) {
    fileList.push(path);
    count++;
    console.log(count)
}
walk(dicpath);

2. 完成Path列表之后,进行数据的读取和入库

function insertRows(id, value) {
    var sql = "insert into cachedata (Path,Base64) values (?,?)";
    var params = [id, value];
    dbhelper.sql.call(this, sql, params,
    function(error, result) {
        console.log("back");
        if (error) console.log(error);
        setItemToMySql()
    })
}
function setItemToMySql() {
    if (count > 0) {
        var path = fileList[count - 1];
        count--;
        console.log(path);
        var base64 = fs.readFileSync(path, "base64");
        insertRows(path, base64)
    }
}
 setItemToMySql();

  目前代码就这些,暂时能完成任务,不过后面需要各种优化。

原文地址:https://www.cnblogs.com/yuxichina/p/2938551.html