Skip to content

Instantly share code, notes, and snippets.

@soyuka
Last active June 24, 2020 13:11
Show Gist options
  • Save soyuka/d421ac28ce97995f608005cf69be4c6b to your computer and use it in GitHub Desktop.
Save soyuka/d421ac28ce97995f608005cf69be4c6b to your computer and use it in GitHub Desktop.
Reactive recursive read directory nodejs
export function directorySize(path: string): Promise<number> {
return readdirRecursive(path)
.reduce((result: any, a: any) => {
result += a.stat.size
return result
}, 0)
}
directorySize('./node_modules')
.then((size) => {
console.log('Total size %d MB', size * 1e-6)
})
/**
*
* ❯ time node lib/fs/fs.js
* Total size 3.848 MB
* node lib/fs/fs.js 0.20s user 0.05s system 124% cpu 0.204 total
**/
import * as fs from 'fs'
import {create} from '@most/create'
import {Stream, of} from 'most'
export function readdir(path: string, options?: any): Stream<any> {
return create((add, end, error) => {
(fs.readdir as any)(path, options, function(err: NodeJS.ErrnoException, files: string[]) {
if (err) {
return error(err)
}
files.map(e => add(`${path}/${e}`))
end()
})
})
}
export function stat(path: string): Stream<any> {
return create((add, end, error) => {
fs.stat(path, function(err: NodeJS.ErrnoException, stats: fs.Stats) {
if (err) {
return error(err)
}
add(stats)
end()
})
})
}
export function readdirRecursive(path: string): Stream<any> {
return readdir(path)
.flatMap((filePath: string) => {
return of(filePath)
.flatMap((e: string) => stat(e))
.map((stat: fs.Stats) => {
return {path: filePath, stat: stat}
})
})
.flatMap((e) => {
return e.stat.isDirectory() ? readdirRecursive(e.path) : of(e)
})
}
readdirRecursive('./node_modules')
.observe((e) => {
console.log(e)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment