Skip to content

Instantly share code, notes, and snippets.

@simov
Last active August 29, 2015 14:21
Show Gist options
  • Save simov/b55de6ec26a98b1eb695 to your computer and use it in GitHub Desktop.
Save simov/b55de6ec26a98b1eb695 to your computer and use it in GitHub Desktop.
Recursive asynchronous streaming of directory
import fs from 'fs'
import path from 'path'
import stream from 'stream'
import bluebird from 'bluebird'
bluebird.promisifyAll(fs)
class Readdirr extends stream.Readable {
constructor(root) {
super()
this._running = false
this._root = root
}
_read() {
if (!this._running) {
this._running = true
this._readdirr(this._root)
.then(() => this.push(null))
.catch((err) => this.emit('error', err))
}
}
async _readdirr (root) {
let items = await fs.readdirAsync(root)
for (let item of items) {
let fpath = path.join(root, item)
, stats = await fs.statAsync(fpath)
if (stats.isDirectory()) {
this.push(fpath)
this.emit('dir', fpath)
await this._readdirr(fpath)
} else {
this.push(fpath)
this.emit('file', fpath)
}
}
}
}
export default Readdirr
if (!process.argv[2]) {
console.log('Specify path to walk!')
process.exit()
}
import path from 'path'
import Readdirr from './readdirr'
import 'babel/polyfill'
let readdirr = new Readdirr(path.resolve(process.argv[2]))
readdirr.resume()
.on('dir', (fpath) =>
console.log('dir ->', fpath.toString('utf8')))
.on('file', (fpath) =>
console.log('file ->', fpath.toString('utf8')))
.on('error', (err) =>
console.log('err ->', err))
.on('end', () =>
console.log('DONE!'))
// $ babel --optional es7.asyncFunctions *.js --out-dir build && iojs build/test.js .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment