Last active
          June 24, 2020 13:11 
        
      - 
      
 - 
        
Save soyuka/d421ac28ce97995f608005cf69be4c6b to your computer and use it in GitHub Desktop.  
    Reactive recursive read directory nodejs
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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 | |
| **/ | 
  
    
      This file contains hidden or 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
    
  
  
    
  | 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