Skip to content

Instantly share code, notes, and snippets.

@iSkore
Forked from liangzan/recursiveRemoveFiles.js
Last active May 5, 2016 15:27
Show Gist options
  • Save iSkore/16dc74848a11e075dd5a85aec6632ce4 to your computer and use it in GitHub Desktop.
Save iSkore/16dc74848a11e075dd5a85aec6632ce4 to your computer and use it in GitHub Desktop.
A Node.js script to remove all files in a directory recursively
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