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

后端 未结 25 1234
天涯浪人
天涯浪人 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:32

    The answer above does not perform a recursive search into the directory though. Here's what I did for a recursive search (using node-walk: npm install walk)

    var walk    = require('walk');
    var files   = [];
    
    // Walker options
    var walker  = walk.walk('./test', { followLinks: false });
    
    walker.on('file', function(root, stat, next) {
        // Add this file to the list of files
        files.push(root + '/' + stat.name);
        next();
    });
    
    walker.on('end', function() {
        console.log(files);
    });
    
    0 讨论(0)
  • 2020-11-22 08:32

    Dependencies.

    var fs = require('fs');
    var path = require('path');
    

    Definition.

    // String -> [String]
    function fileList(dir) {
      return fs.readdirSync(dir).reduce(function(list, file) {
        var name = path.join(dir, file);
        var isDir = fs.statSync(name).isDirectory();
        return list.concat(isDir ? fileList(name) : [name]);
      }, []);
    }
    

    Usage.

    var DIR = '/usr/local/bin';
    
    // 1. List all files in DIR
    fileList(DIR);
    // => ['/usr/local/bin/babel', '/usr/local/bin/bower', ...]
    
    // 2. List all file names in DIR
    fileList(DIR).map((file) => file.split(path.sep).slice(-1)[0]);
    // => ['babel', 'bower', ...]
    

    Please note that fileList is way too optimistic. For anything serious, add some error handling.

    0 讨论(0)
  • 2020-11-22 08:33

    if someone still search for this, i do this:

    import fs from 'fs';
    import path from 'path';
    
    const getAllFiles = dir =>
        fs.readdirSync(dir).reduce((files, file) => {
            const name = path.join(dir, file);
            const isDirectory = fs.statSync(name).isDirectory();
            return isDirectory ? [...files, ...getAllFiles(name)] : [...files, name];
        }, []);

    and its work very good for me

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 08:36

    This will work and store the result in test.txt file which will be present in the same directory

      fs.readdirSync(__dirname).forEach(file => {
        fs.appendFileSync("test.txt", file+"\n", function(err){
        })
    })
    
    0 讨论(0)
  • 2020-11-22 08:37

    You can use the fs.readdir or fs.readdirSync methods.

    fs.readdir

    const testFolder = './tests/';
    const fs = require('fs');
    
    fs.readdir(testFolder, (err, files) => {
      files.forEach(file => {
        console.log(file);
      });
    });
    

    fs.readdirSync

    const testFolder = './tests/';
    const fs = require('fs');
    
    fs.readdirSync(testFolder).forEach(file => {
      console.log(file);
    });
    

    The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

    The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.

    0 讨论(0)
提交回复
热议问题