Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
Bjorn Reppen Avatar asked May 26 '17 11:05

Bjorn Reppen


People also ask

How do I check the extension of a node js file?

The path. extname() method returns the extension of a file path.

What is __ filename in node?

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

How can I get file extensions with JavaScript?

Using substring() and lastIndexOf() method: This returns the index in the string where the string passed last occurs. The last index can be found by passing a period(.) to this method. The index is passed on to the substring() method, which returns the string from the period(.) to the end. This is the file extension.


2 Answers

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.

like image 152
Freeman Lambda Avatar answered Sep 22 '22 09:09

Freeman Lambda


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... }) 
like image 24
Lazyexpert Avatar answered Sep 25 '22 09:09

Lazyexpert