Skip to content

Instantly share code, notes, and snippets.

@ilio
Created June 10, 2018 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilio/7e36f47701df7f2342b7c257f704b902 to your computer and use it in GitHub Desktop.
Save ilio/7e36f47701df7f2342b7c257f704b902 to your computer and use it in GitHub Desktop.
node copy files recursive async
awaitable = (func, ...args) => {
return new Promise(resolve => {
func.apply(this, [...args, (...a) => {
if(a.length === 1){
return resolve(a[0]);
}
if(a.length === 2){
return resolve(a[1]);
}
return resolve(a);
}]);
});
}
const copyRecursive = async (src, dest) => {
const exists = await awaitable(fs.exists, src);
const stats = exists && await awaitable(fs.stat, src);
const isDirectory = exists && stats.isDirectory();
if (isDirectory) {
await awaitable(fs.mkdir, dest);
const dir = (await awaitable(fs.readdir, src));
for(const childItemName of dir){
await copyRecursive(
path.join(src, childItemName),
path.join(dest, childItemName)
);
}
} else {
const readStream = fs.createReadStream(src);
readStream.pipe(fs.createWriteStream(dest));
await new Promise(resolve => {
readStream.on('end', () => {
resolve();
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment