Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement