---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

node遍历目录文件

前端开发 蚂蚁 991℃ 0评论

基于Node.JS索引mp3 ID3 tag信息并存储入MySQL数据库

传统的同步方法:
// sync version
function walkSync(currentDirPath, callback) {
    var fs = require('fs'),
        path = require('path');
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if (stat.isDirectory()) {
            walkSync(filePath, callback);
        }
    });
}
walkSync('path/to/root/dir', function(filePath, stat) {
    // do something with "filePath"...
});

异步方法:
// async version with basic error handling
function walk(currentDirPath, callback) {
    var fs = require('fs'),
        path = require('path');
    fs.readdir(currentDirPath, function (err, files) {
        if (err) {
            throw new Error(err);
        }
        files.forEach(function (name) {
            var filePath = path.join(currentDirPath, name);
            var stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, stat);
            } else if (stat.isDirectory()) {
                walk(filePath, callback);
            }
        });
    });
}
walk('path/to/root/dir', function(filePath, stat) {
    // do something with "filePath"...
});

转载请注明:有爱前端 » node遍历目录文件

喜欢 (2)or分享 (0)