Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Dec 18, 2015

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

@tmamedbekov

This comment has been minimized.

Copy link

commented Jan 4, 2017

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

@eyahm8

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented May 15, 2017

@tmamedbekov

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

This comment has been minimized.

Copy link

commented Sep 9, 2017

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

@stancil-marcus

This comment has been minimized.

Copy link

commented Mar 26, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.