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
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);
});
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
This is not covered by Node core. You can check out this module for what you are after.
npm i 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.
})
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)
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');
});