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

@thesparrow thesparrow 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

@tmamedbekov tmamedbekov 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

@eyahm8 eyahm8 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

@khanxc khanxc 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

@divinediscipline divinediscipline commented Sep 9, 2017

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

@stancil-marcus

This comment has been minimized.

Copy link

@stancil-marcus stancil-marcus 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.

@artem-web-dev

This comment has been minimized.

Copy link

@artem-web-dev artem-web-dev commented Dec 16, 2019

how to do this with recursion?

@nanmcpe

This comment has been minimized.

Copy link

@nanmcpe nanmcpe commented Mar 13, 2020

Thanks for this 🙏🏻

@Uruu91

This comment has been minimized.

Copy link

@Uruu91 Uruu91 commented Jun 5, 2020

Thanks you!!

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