Skip to content

Instantly share code, notes, and snippets.

@shenjunru
Created May 7, 2018 05:17
Show Gist options
  • Save shenjunru/2cb5b993a1b437935f77932d2bdab20e to your computer and use it in GitHub Desktop.
Save shenjunru/2cb5b993a1b437935f77932d2bdab20e to your computer and use it in GitHub Desktop.
node.js remove directory recursively
// remove directory recursively
const { promisify } = require('util');
const $fsys = require('fs');
const $path = require('path');
const fstat = promisify($fsys.stat);
const lsdir = promisify($fsys.readdir);
const mkdir = promisify($fsys.mkdir);
const rmdir = promisify($fsys.rmdir);
const unlink = promisify($fsys.unlink);
const remove = async (path) => {
const stat = await fstat(path);
if (stat.isFile()) {
return unlink(path);
}
if (stat.isDirectory()) {
const files = await lsdir(path);
await Promise.all(files.map(f => $path.resolve(path, f)).map(clean));
return rmdir(path);
}
};
exports.remove = async (path) => {
if ($fsys.existsSync(path)) {
await remove(path);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment