From 919910ae413bf1e7c7c0ce77b8f6d5c133e714d3 Mon Sep 17 00:00:00 2001 From: Andy Balaam Date: Thu, 26 Dec 2013 09:26:06 +0000 Subject: [PATCH] Refactor walk_dir to use smaller functions. --- www/index/tvindex.js | 140 ++++++++++++++++++++++++++++----------------------- 1 file changed, 77 insertions(+), 63 deletions(-) rewrite www/index/tvindex.js (70%) diff --git a/www/index/tvindex.js b/www/index/tvindex.js dissimilarity index 70% index 0058d75..0a2e6cb 100644 --- a/www/index/tvindex.js +++ b/www/index/tvindex.js @@ -1,63 +1,77 @@ - -exports.walk_dir = function( fs, dir, callback ) -{ - var ret_files = []; - var ret_err = null; - - function impl( queue ) - { - console.log( queue ); - if ( ret_err ) - { - return; - } - else if ( queue.length === 0 ) - { - ret_files.sort(); - callback( null, ret_files ); - } - else - { - var item = queue.pop(); - fs.stat( item, function( err, stats ) - { - if ( err ) - { - callback( err ); - ret_err = true; - } - else if ( stats.isDirectory() ) - { - fs.readdir( item, function( err, subitems ) - { - if ( err ) - { - callback( err ); - ret_err = true; - } - else - { - for ( var i = 0; i < subitems.length; ++i ) - { - queue.push( item + "/" + subitems[i] ); - } - impl( queue ); - } - } ); - } - else - { - if ( item.match( /.*\.mp4/ ) ) - { - ret_files.push( item ); - } - impl( queue ); - } - } ); - } - } - - impl( [ dir ] ); - -} - + +exports.walk_dir = function( fs, dir, callback ) +{ + var ret_files = []; + var ret_err = null; + + function implDir( queue, item ) + { + fs.readdir( item, function( err, subitems ) + { + if ( err ) + { + callback( err ); + ret_err = true; + } + else + { + for ( var i = 0; i < subitems.length; ++i ) + { + queue.push( item + "/" + subitems[i] ); + } + impl( queue ); + } + } ); + } + + function implFile( queue, item ) + { + if ( item.match( /.*\.mp4/ ) ) + { + ret_files.push( item ); + } + impl( queue ); + } + + function implItem( queue, item ) + { + fs.stat( item, function( err, stats ) + { + if ( err ) + { + ret_err = true; + callback( err ); + } + else if ( stats.isDirectory() ) + { + implDir( queue, item ); + } + else + { + implFile( queue, item ); + } + } ); + } + + function impl( queue ) + { + if ( ret_err ) + { + return; + } + else if ( queue.length === 0 ) + { + ret_files.sort(); + callback( null, ret_files ); + } + else + { + var item = queue.pop(); + implItem( queue, item ); + } + } + + impl( [ dir ] ); + +} + -- 2.11.4.GIT