How do I get a list of files with specific file extension using node.js?
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...
})