Last active
April 30, 2017 13:14
-
-
Save keksipurkki/1a17db956b6d428ea01ffe4b082ef8f8 to your computer and use it in GitHub Desktop.
Recursively find files with NodeJS
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
#!/usr/bin/env node | |
const fs = require('fs'); | |
const path = require('path'); | |
const Readable = require('readable-stream').Readable; | |
function complements(arr, predicate) { | |
const out = [[],[]]; | |
arr.forEach(e => out[Number(!!predicate(e))].push(e)); | |
return out; | |
} | |
function isDirectory(path) { | |
return fs.lstatSync(path).isDirectory(); | |
} | |
function getFiles(root, stream) { | |
if (!(stream instanceof Readable)) { | |
stream = Readable({objectMode: true}); | |
stream._read = () => {}; | |
} | |
fs.readdir(root, (err, paths) => { | |
if (err) throw err; | |
paths = paths.map(i => path.join(root, i)); | |
const [ files, dirs ] = complements(paths, isDirectory); | |
files.forEach(f => stream.push(f)); | |
dirs.forEach(d => getFiles(d, stream)); | |
}); | |
return stream; | |
} | |
getFiles(process.cwd()).on('data', file => { | |
console.log(file); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment