The node fs package has the following methods to list a directory:
fs.readdir(path, [callback]) Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path) Synchronous readdir(3). Returns an array of filenames excluding '.' and '..
But how do I get a list of files matching a file specification, for example *.txt?
The path. extname() method returns the extension of a file path.
The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.
Using substring() and lastIndexOf() method: This returns the index in the string where the string passed last occurs. The last index can be found by passing a period(.) to this method. The index is passed on to the substring() method, which returns the string from the period(.) to the end. This is the file extension.
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.
const path = require('path'); const EXTENSION = '.txt'; const targetFiles = files.filter(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.
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 => path.extname(el) === '.txt') // do something with your files, by the way they are just filenames... })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With