Created
February 24, 2014 19:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
}); |
if I want it to filter only (.txt) files, what should I change?
@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.
function extension(element) {
var extName = path.extname(element);
return extName === '.txt' // change to whatever extensions you want
};
Thanks. This helped me in solving my freecodecamp nodejs learnyounode Challenge.
How would you write the path in node.js is your operating system is Windows? My path can't be read.
how to do this with recursion?
Thanks for this 🙏🏻
Thanks you!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this! Still learning how to utilize the node.js api.