46

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?

1
  • 1
    You'll get the list of all files the files in directory in your callback argument. You can filter that. Commented May 26, 2017 at 11:03

5 Answers 5

65

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Almost correct. You need to lowercase the extension, as some files may use uppercased, e.g: .TXT
to someone doing copy/paste this answer is missing the actual reading of the directory which would be the case on the answer of Lazyexpert
32

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...
})

14 Comments

Don't parse the filename with a regex, use path.extname.
Does it make any difference? Or maybe you think it's faster than regexp?
I agree, in some complex cases its all true. But this one, seriously: /\.txt$/, takes time to read and understand?
I wonder, how many time it took you to read and understand that regexp? How many ms? I repeat, in most cases - I totally agree. But the simpliest... what are we even talking about...?
You can write 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1, that is 10. Everyone can add right? It has 0 complexity? But it is a waste of time for the reader. Just write 10. Having to do that sum in your head distracts the reader from understanding how 10 fits into the rest of the code.
|
9

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.
})

Comments

7

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);
});

2 Comments

Text file extension can also be uppercased (e.g: .TXT)
yes you are right. Thanks for pointing out the possible problem :)
1
const fs = require('fs');
const path = require('path');
    
// Path to the directory(folder) to look into
const dirPath = path.resolve(`${__dirname}../../../../../tests_output`);
        
// Read all files with .txt extension in the specified folder above
const filesList = fs.readdirSync(dirPath, (err, files) => files.filter((e) => path.extname(e).toLowerCase() === '.txt'));
        
// Read the content of the first file with .txt extension in the folder
const data = fs.readFileSync(path.resolve(`${__dirname}../../../../../tests_output/${filesList[0]}`), 'utf8');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.