find file with wild card matching

后端 未结 5 1684
滥情空心
滥情空心 2020-12-08 18:31

In node.js, can I list files with wild card matching like

fs.readdirSync(\'C:/tmp/*.csv\')?

I did not find the information on wild card ma

相关标签:
5条回答
  • 2020-12-08 18:32

    If glob is not quite what you want, or a little confusing, there is also glob-fs. The documentation covers many usage scenarios with examples.

    // sync 
    var files = glob.readdirSync('*.js', {});
    
    // async 
    glob.readdir('*.js', function(err, files) {
      console.log(files);
    });
    
    // stream 
    glob.readdirStream('*.js', {})
      .on('data', function(file) {
        console.log(file);
      });
    
    // promise 
    glob.readdirPromise('*.js')
      .then(function(files) {
        console.log(file);
      });
    
    0 讨论(0)
  • 2020-12-08 18:36

    If you don't want to add a new dependency to your project (like glob), you can use plain js/node functions, like:

    var files = fs.readdirSync('C:/tmp').filter(fn => fn.endsWith('.csv'));
    

    Regex may help in more complex comparisons

    0 讨论(0)
  • This is not covered by Node core. You can check out this module for what you are after.

    Setup

    npm i glob
    

    Usage

    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)
  • 2020-12-08 18:46

    Just in case you want to search files by regex (for complex matches), then consider using file-regex, which supports recursive search and concurrency control (for faster results).

    Sample usage

    import FindFiles from 'file-regex'
    
    // This will find all the files with extension .js
    // in the given directory
    const result = await FindFiles(__dirname, /\.js$/);
    console.log(result)
    
    0 讨论(0)
  • 2020-12-08 18:50

    dont reinvent the wheel, if you are on *nix the ls tool can easily do this (node api docs)

    var options = {
      cwd: process.cwd(),
    }
    require('child_process')
    .exec('ls -1 *.csv', options, function(err, stdout, stderr){
      if(err){ console.log(stderr); throw err };
      // remove any trailing newline, otherwise last element will be "":
      stdout = stdout.replace(/\n$/, '');
      var files = stdout.split('\n');
    });
    
    0 讨论(0)
提交回复
热议问题