Created
June 23, 2023 10:16
-
-
Save amanpreet-dev/e20497a53c82eff3cc70fbe41215d57f to your computer and use it in GitHub Desktop.
Recursively moving files in a directory with Node.js and TypeScript
This file contains 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
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)); |
This file contains 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
{ | |
"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