54 lines
2.1 KiB
JavaScript
54 lines
2.1 KiB
JavaScript
const fs = require('fs');
|
||
const path = require('path');
|
||
const readline = require('readline');
|
||
|
||
/**
|
||
* 指定CSVファイルを読み込み、各行ごとに
|
||
* 1つ目の名前で移動先ベースディレクトリにフォルダ作成(存在すればスキップ)、
|
||
* 2つ目の名前のファイルを検索元ベースディレクトリからそのフォルダへ移動
|
||
* @param {string} csvFilePath CSVファイルのパス
|
||
* @param {string} srcBaseDir 検索元ベースディレクトリ
|
||
* @param {string} destBaseDir 移動先ベースディレクトリ
|
||
*/
|
||
async function moveFilesByCsv(csvFilePath, srcBaseDir, destBaseDir) {
|
||
const rl = readline.createInterface({
|
||
input: fs.createReadStream(csvFilePath),
|
||
crlfDelay: Infinity
|
||
});
|
||
|
||
for await (const line of rl) {
|
||
if (!line.trim()) continue; // 空行スキップ
|
||
const [folderName, fileName] = line.split(',').map(s => s.trim());
|
||
if (!folderName || !fileName) continue;
|
||
const folderPath = path.join(destBaseDir, folderName);
|
||
const filePath = path.join(srcBaseDir, fileName);
|
||
const destPath = path.join(folderPath, fileName);
|
||
|
||
// フォルダ作成(存在すればスキップ)
|
||
if (!fs.existsSync(folderPath)) {
|
||
fs.mkdirSync(folderPath, { recursive: true });
|
||
console.log(`フォルダ作成: ${folderPath}`);
|
||
}
|
||
// ファイル移動
|
||
if (fs.existsSync(filePath)) {
|
||
fs.renameSync(filePath, destPath);
|
||
console.log(`ファイル移動: ${filePath} → ${destPath}`);
|
||
} else {
|
||
console.warn(`ファイルが存在しません: ${filePath}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
module.exports = { moveFilesByCsv };
|
||
|
||
// 実行例: コマンドライン引数でCSVファイル名指定可
|
||
if (require.main === module) {
|
||
const csvFile = process.argv[2] || 'sample.csv';
|
||
const srcBaseDir = process.argv[3] || __dirname;
|
||
const destBaseDir = process.argv[4] || __dirname;
|
||
moveFilesByCsv(csvFile, srcBaseDir, destBaseDir)
|
||
.then(() => console.log('完了'))
|
||
.catch(err => console.error('エラー:', err));
|
||
}
|