Skip to content

Instantly share code, notes, and snippets.

@sabesansathananthan
Created September 8, 2022 18:45
Show Gist options
  • Save sabesansathananthan/943f56ef3ed34534f0f4d697c675646d to your computer and use it in GitHub Desktop.
Save sabesansathananthan/943f56ef3ed34534f0f4d697c675646d to your computer and use it in GitHub Desktop.
How to copy files and folders in Node.js?
/**
* Copy the src folder to the dest folder
* @param {string} src
* @param {string} dest
* @param {function} callback
*/
const copyDir = (src, dest, callback) => {
const copy = (copySrc, copyDest) => {
fs.readdir(copySrc, (err, list) => {
if (err) {
callback(err);
return;
}
list.forEach((item) => {
const ss = path.resolve(copySrc, item);
fs.stat(ss, (err, stat) => {
if (err) {
callback(err);
} else {
const curSrc = path.resolve(copySrc, item);
const curDest = path.resolve(copyDest, item);
if (stat.isFile()) {
// file, copy directly
fs.createReadStream(curSrc).pipe(fs.createWriteStream(curDest));
} else if (stat.isDirectory()) {
// directory, recursively
fs.mkdirSync(curDest, { recursive: true });
copy(curSrc, curDest);
}
}
});
});
});
};
fs.access(dest, (err) => {
if (err) {
// If the target directory does not exist, create it
fs.mkdirSync(dest, { recursive: true });
}
copy(src, dest);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment