The node fs package has the following methods to list a directory:
fs.readdir(path, [callback]) Asynchronous readdir(3). Reads the
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...
})
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);
});
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.
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.
})