-
-
Save iSkore/16dc74848a11e075dd5a85aec6632ce4 to your computer and use it in GitHub Desktop.
A Node.js script to remove all files in a directory recursively
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
const fs = require( 'fs' ) | |
, path = require( 'path' ) | |
, _ = require( 'lodash' ); | |
let rootPath = "/path/to/remove"; | |
rmRF(rootPath); | |
function rmRF( dirPath ) { | |
fs.readdir( dirPath, ( err, files ) => { | |
if ( err ) console.log( JSON.stringify( err ) ); | |
else { | |
if ( files.length === 0 ) { | |
fs.rmdir( dirPath, ( err ) => { | |
if ( err ) console.log( JSON.stringify( err ) ); | |
else { | |
let parentPath = path.normalize( dirPath + '/..' ) + '/'; | |
if ( parentPath != path.normalize( rootPath ) ) { | |
rmRF( parentPath ); | |
} | |
} | |
} ); | |
} else { | |
_.each( files, ( file ) => { | |
let filePath = dirPath + file; | |
fs.stat( filePath, ( err, stats ) => { | |
if ( err ) { | |
console.log( JSON.stringify( err ) ); | |
} else { | |
if ( stats.isFile() ) { | |
fs.unlink( filePath, ( err ) => { | |
if ( err ) console.log( JSON.stringify( err ) ); | |
} ); | |
} | |
if ( stats.isDirectory() ) { | |
rmRF( filePath + '/' ); | |
} | |
} | |
}); | |
}); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment