Created
June 10, 2018 18:38
-
-
Save ilio/7e36f47701df7f2342b7c257f704b902 to your computer and use it in GitHub Desktop.
node copy files recursive async
This file contains hidden or 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
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