Skip to content

Instantly share code, notes, and snippets.

@ThomasChan
Created March 22, 2024 02:37
Show Gist options
  • Save ThomasChan/2cdd79d167d270af887cb7038ec1bee7 to your computer and use it in GitHub Desktop.
Save ThomasChan/2cdd79d167d270af887cb7038ec1bee7 to your computer and use it in GitHub Desktop.
Batch move files from SD card to OneDrive cloud
/**
* @author ThomasChan
* @usage deno run --allow-read --allow-write --unstable moveFiles.ts
*/
// Define SD card and OneDrive folder absolute path
const sdCardPath = '/Volumes/Untitled/MP_ROOT'; // replace to your sd card full absolute path
const oneDrivePath = '/Users/<yourusername>/OneDrive'; // replace to your OneDrive full absolute path
// Create folder if not exists
async function ensureFolderExists(folderPath) {
try {
const stat = await Deno.stat(folderPath);
if (!stat.isDirectory) {
console.error(`Error: ${folderPath} is not a directory`);
Deno.exit(1);
}
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// 如果文件夹不存在,创建文件夹
await Deno.mkdir(folderPath, { recursive: true });
} else {
throw error;
}
}
}
async function run() {
console.log('Scanning SD card...');
for await (const entry of Deno.readDir(sdCardPath)) {
if (entry.isDirectory) {
const dirPath = `${sdCardPath}/${entry.name}`;
console.log(`Processing directory: ${dirPath}`);
for await (const file of Deno.readDir(dirPath)) {
if (file.isFile) {
console.log(`Processing file: ${file.name}`);
try {
const filePath = `${dirPath}/${file.name}`;
const fileInfo = await Deno.stat(filePath);
const createdDate = fileInfo.birthtime || fileInfo.mtime;
// organize folder by YYYYMM
const targetDir = `${oneDrivePath}/${createdDate.getFullYear()}${String(createdDate.getMonth() + 1).padStart(2, '0')}`;
await ensureFolderExists(targetDir);
const targetPath = `${targetDir}/${file.name}`;
// Deno cannot directly rename file between difference hardware system, use copy + remove instead
await Deno.copyFile(filePath, targetPath);
await Deno.remove(filePath);
console.log(`Moved ${file.name} to ${targetPath}`);
} catch (e) {
console.log(e.messages)
console.log(`Unable to copy/remove ${file.name}`);
}
}
}
}
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment