How do I get a list of files with specific file extension using node.js?

后端 未结 4 1341
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 00:37

The node fs package has the following methods to list a directory:

fs.readdir(path, [callback]) Asynchronous readdir(3). Reads the

相关标签:
4条回答
  • 2020-12-31 01:11

    Basically, you do something like this:

    const path = require('path')
    const fs = require('fs')
    
    const dirpath = path.join(__dirname, '/path')
    
    fs.readdir(dirpath, function(err, files) {
      const txtFiles = files.filter(el => /\.txt$/.test(el))
      // do something with your files, by the way they are just filenames...
    })
    
    0 讨论(0)
  • 2020-12-31 01:13

    I used the following code and its working fine:

    var fs = require('fs');
    var path = require('path');
    var dirPath = path.resolve(__dirname); // path to your directory goes here
    var filesList;
    fs.readdir(dirPath, function(err, files){
      filesList = files.filter(function(e){
        return path.extname(e).toLowerCase() === '.txt'
      });
      console.log(filesList);
    });
    
    0 讨论(0)
  • 2020-12-31 01:16

    You could filter they array of files with an extension extractor function. The path module provides one such function, if you don't want to write your own string manipulation logic or regex.

    var path = require('path');
    
    var EXTENSION = '.txt';
    
    var targetFiles = files.filter(function(file) {
        return path.extname(file).toLowerCase() === EXTENSION;
    });
    

    EDIT As per @arboreal84's suggestion, you may want to consider cases such as myfile.TXT, not too uncommon. I just tested it myself and path.extname does not do lowercasing for you.

    0 讨论(0)
  • 2020-12-31 01:36

    fs doesn't support filtering itself but if you don't want to filter youself then use glob

    var glob = require('glob');
    
    // options is optional
    glob("**/*.js", options, function (er, files) {
      // files is an array of filenames.
      // If the `nonull` option is set, and nothing
      // was found, then files is ["**/*.js"]
      // er is an error object or null.
    })
    
    0 讨论(0)
提交回复
热议问题