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

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

    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.

提交回复
热议问题