在Javascript中获取文件夹和文件列表的最佳方法 [英] best way to get folder and file list in Javascript

查看:101
本文介绍了在Javascript中获取文件夹和文件列表的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node-webkit,并试图让用户选择一个文件夹,我将返回该文件夹的目录结构并递归获取其子级.

I'm using node-webkit, and am trying to have a user select a folder, and I'll return the directory structure of that folder and recursively get its children.

我使用这段代码(在 Angular 控制器中)相当简单地完成了这项工作.

I've got this working fairly simply with this code (in an Angular Controller).

var fs = require('fs');

$scope.explorer=[];
$scope.openFile = function(){
    $scope.explorer = [tree_entry($scope.path)];    
    get_folder($scope.path, $scope.explorer[0].children);
};

function get_folder(path, tree){
    fs.readdir(path, function(err,files){
        if (err) return console.log(err);

        files.forEach( function (file,idx){
            tree.push(tree_entry(file));
            fs.lstat(path+'/'+file,function(err,stats){
                if(err) return console.log(err);
                if(stats.isDirectory()){
                    get_folder(path+'/'+file,tree[idx].children);
                }
            });
        });
    });
    console.log($scope.explorer);

    return;
}

function tree_entry(entry){
    return { label : entry, children: []}
}

以一个中等大小的文件夹为例,该文件夹有 22 个子文件夹,深度约为 4 级,需要几分钟才能获得整个目录结构.

Taking a moderate sized folder with 22 child folders and about 4 levels deep, it is taking a few minutes to get the entire directory structure.

我在这里显然做错了什么吗?我不敢相信需要那么长时间,因为我正在使用内置的 Node fs 方法.或者有没有办法在不触及每个文件的情况下获取目录的全部内容?

Is there something that I'm obviously doing wrong here? I can't believe it takes that long, seeing as I'm using the built in Node fs methods. Or is there a way to get the entire contents of a directory without touching each and every file?

我希望能够对文件名一直使用 Angular 过滤器,也可能对内容使用 Angular 过滤器,因此延迟处理整个树不太可能是可行的解决方案.

I'm going to want to be able to use an Angular filter on the file names all the way down the tree, and possibly on the contents too, so delaying processing the entire tree isn't likely a solution that would work.

推荐答案

在我的项目中,我使用此功能来获取大量文件.它非常快(将 require("fs") 放在外面以使其更快):

In my project I use this function for getting huge amount of files. It's pretty fast (put require("fs") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

用法很明确:

_getAllFilesFromFolder(__dirname + "folder");

这篇关于在Javascript中获取文件夹和文件列表的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆