How do you get a list of the names of all files present in a directory in Node.js?

后端 未结 25 1166
天涯浪人
天涯浪人 2020-11-22 07:47

I\'m trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

25条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 08:35

    Here's a simple solution using only the native fs and path modules:

    // 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);
            }
        });
    }
    

    or async version (uses fs.readdir instead):

    // 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);
                }
            });
        });
    }
    

    Then you just call (for sync version):

    walkSync('path/to/root/dir', function(filePath, stat) {
        // do something with "filePath"...
    });
    

    or async version:

    walk('path/to/root/dir', function(filePath, stat) {
        // do something with "filePath"...
    });
    

    The difference is in how node blocks while performing the IO. Given that the API above is the same, you could just use the async version to ensure maximum performance.

    However there is one advantage to using the synchronous version. It is easier to execute some code as soon as the walk is done, as in the next statement after the walk. With the async version, you would need some extra way of knowing when you are done. Perhaps creating a map of all paths first, then enumerating them. For simple build/util scripts (vs high performance web servers) you could use the sync version without causing any damage.

提交回复
热议问题