This is really complex. Did you have a look at [rimraf](https://www.npmjs.org/package/rimraf)?