First i want to describe the problem: i have a directory tree (depth = 3) which contains several directories and files. Some of those files have .txt extension and some .mp4. I want to copy only .mp4 files in new directory with same hierarchy as it was in source directory (in other words, i don't want to copy all mp4 files in one folder, i want to copy all directories as it is and then copy mp4 files). The question is: how to copy those files not in series, but in parallel? Here is my code:
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const sourceDir = process.argv[2];
const stat = promisify(fs.stat);
const copy = promisify(fs.copyFile);
const mkdir = promisify(fs.mkdir);
const readdir = promisify(fs.readdir);
const targetDir = path.join(__dirname, 'only-mp4');
// creating root folder, all files will be copied here
(async () => {
await mkdir(targetDir);
})();
const copyMediaFiles = async (node) => {
try {
const stats = await stat(node);
if (stats.isDirectory()) {
let children = await readdir(node);
// constructing new paths
children = children.map((child) => path.join(node, child));
// "copying" file hierarchy (basically just recreating same file hierarchy in target directory)
children.forEach((child) => {
const courseDirs = child.split('/').slice(4, 7).join('/');
mkdir(path.join(targetDir, courseDirs), { recursive: true });
});
// running this function for all children recursively in parallel
const promises = children.map(copyMediaFiles);
await Promise.all(promises);
}
const ext = path.extname(node);
const filename = path.basename(node);
// if file extension == mp4 then copy that file in target directory
if (ext === '.mp4') {
await copy(
node,
path.join(
targetDir,
path.dirname(node).split('/').slice(4).join('/'),
filename
)
);
console.log('File copied: ', filename);
}
return;
} catch (error) {
console.log(error);
}
};
copyMediaFiles(sourceDir).then(() => console.log('All mp4 files copied'));
Yes, it's working, but i'm not sure i did it right. Any advise one that? What i did wrong here? And i'm not sure i'm traversing this tree right.