Bjorn Reppen
Bjorn Reppen

Reputation: 22769

How do I get a list of files with specific file extension using node.js?

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?

Upvotes: 46

Views: 77196

Answers (5)

Joshua Gato
Joshua Gato

Reputation: 59

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

Upvotes: 1

Freeman Lambda
Freeman Lambda

Reputation: 3655

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.

Upvotes: 64

Lazyexpert
Lazyexpert

Reputation: 3154

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

Upvotes: 32

Abdul Samad
Abdul Samad

Reputation: 441

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

Upvotes: 7

Cruiser KID
Cruiser KID

Reputation: 1280

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

Upvotes: 9

Related Questions