Skip to content

Instantly share code, notes, and snippets.

@amanpreet-dev
Created June 23, 2023 10:16
Show Gist options
  • Save amanpreet-dev/e20497a53c82eff3cc70fbe41215d57f to your computer and use it in GitHub Desktop.
Save amanpreet-dev/e20497a53c82eff3cc70fbe41215d57f to your computer and use it in GitHub Desktop.
Recursively moving files in a directory with Node.js and TypeScript
import fs from "fs";
import path from "path";
function moveFiles(sourceDir: string, targetDir: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.readdir(sourceDir, (err, files) => {
if (err) {
reject(err);
return;
}
files.forEach((file) => {
const oldPath = path.join(sourceDir, file);
const newPath = path.join(targetDir, file);
const stat = fs.lstatSync(oldPath);
if (stat.isDirectory()) {
moveFiles(oldPath, targetDir)
.then(() => {
if (files.indexOf(file) === files.length - 1) {
resolve();
}
})
.catch((err) => reject(err));
} else if (stat.isFile()) {
fs.rename(oldPath, newPath, (err) => {
if (err) {
reject(err);
return;
}
if (files.indexOf(file) === files.length - 1) {
resolve();
}
});
}
});
});
});
}
moveFiles("Source Folder", "Target Folder")
.then(() => console.log("All files moved successfully."))
.catch((err) => console.error(err));
{
"name": "recursive-dirs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-node": "^10.9.1",
"typescript": "^5.1.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment