Skip to content

Instantly share code, notes, and snippets.

@oliverswitzer
Created February 24, 2014 19:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oliverswitzer/9194629 to your computer and use it in GitHub Desktop.
Save oliverswitzer/9194629 to your computer and use it in GitHub Desktop.
An example of a script that will filter files with certain extensions in Node.js
// asynchDirList.js
var fs = require('fs'); //require node filesystem module
var path = require('path'); //require node path module (a couple of tools for reading path names)
var pathSupplied = process.argv[2];
var extFilter = process.argv[3];
function extension(element) {
var extName = path.extname(element);
return extName === '.' + extFilter;
};
fs.readdir(pathSupplied, function(err, list) {
list.filter(extension).forEach(function(value) {
console.log(value);
});
});
@thesparrow
Copy link

Thank you for this! Still learning how to utilize the node.js api.

@tmamedbekov
Copy link

if I want it to filter only (.txt) files, what should I change?

@nibunabu
Copy link

nibunabu commented Feb 26, 2017

@tmamedbekov it is already taking the extension as the second argument(index 3), first argument(index 2) being the path, so for txt files it would be "/home/foo/bar txt"

If you really want to change it to always and only take .txt files, change extFilter in the code to txt.

@khanxc
Copy link

khanxc commented May 15, 2017

@tmamedbekov

function extension(element) {
  var extName = path.extname(element);
  return extName === '.txt' // change to whatever extensions you want
};

@divinediscipline
Copy link

Thanks. This helped me in solving my freecodecamp nodejs learnyounode Challenge.

@stancil-marcus
Copy link

How would you write the path in node.js is your operating system is Windows? My path can't be read.

@artem-web-dev
Copy link

how to do this with recursion?

@nanthanwa
Copy link

Thanks for this 🙏🏻

@njralonso
Copy link

Thanks you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment