0%

javascript-file-collecting

JavaScript File Collecting

今天收到老婆的一个需求,她有一个文件夹,里面包含若干文件和子文件夹,子文件夹又包含文件及子文件夹,她需要将这些文件全部收集到一个文件夹中。收集后的文件要从1开始命名,依次递增。我想到了 Node.js,可以使用 Node.js 来实现这个需求。

代码实现 - 百度文心一言版

这个版本一开始错误百出,经过我修改后才能使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const fs = require('fs').promises;
const path = require('path');

let fileIndex = 3001;

async function copyAndRenameFiles(srcDir, destDir) {
try {
// 确保目标目录存在
await fs.access(destDir);
} catch {
// 如果不存在,则创建目标目录
await fs.mkdir(destDir, { recursive: true });
}

// 读取srcDir中的所有文件和文件夹
const entries = await fs.readdir(srcDir, { withFileTypes: true });

for (const entry of entries) {
const srcPath = path.join(srcDir, entry.name);
console.log(srcPath);

if (entry.isDirectory()) {
// 如果是文件夹,则递归调用
await copyAndRenameFiles(srcPath, destDir);
} else if (entry.isFile()) {
const destBaseName = `${fileIndex}`; // 新文件的基本名称
const destExtname = path.extname(entry.name); // 获取原文件的扩展名
const destPath = path.join(destDir, `${destBaseName}${destExtname}`); // 目标文件完整路径
// 如果是文件,则复制到目标文件夹并重命名
await fs.copyFile(srcPath, destPath);
fileIndex++; // 更新文件索引
}
}

return fileIndex; // 返回下一个可用的文件索引
}

// 使用示例
const sourceFolder = 'xxx'; // 顶层文件夹路径
const destinationFolder = 'xxx'; // 目标文件夹路径

// 从1开始编号
copyAndRenameFiles(sourceFolder, destinationFolder)
.then((finalFileIndex) => {
console.log(
`所有文件已成功复制到目标文件夹,并从1开始重新编号到${
finalFileIndex - 1
}。`
);
})
.catch((error) => {
console.error('在复制过程中发生错误:', error);
});

代码实现-ChatGPT4

这个版本一次通过,一行未改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const fs = require('fs').promises;
const path = require('path');

// 这里使用参数arrayOfFiles递归收集所有文件,思路很巧妙。
async function getAllFiles(dirPath, arrayOfFiles) {
const files = await fs.readdir(dirPath);

arrayOfFiles = arrayOfFiles || [];

for (const file of files) {
const filepath = path.join(dirPath, file);
const stat = await fs.stat(filepath);

if (stat.isDirectory()) {
arrayOfFiles = await getAllFiles(filepath, arrayOfFiles);
} else {
arrayOfFiles.push(filepath);
}
}

return arrayOfFiles;
}

async function copyFilesWithNumberedNames(sourceDir, targetDir) {
try {
// Create target directory if it does not exist
await fs.mkdir(targetDir, { recursive: true });

// Get all files from the source directory
const filesToCopy = await getAllFiles(sourceDir);

// Copy each file with a new numbered name
let fileNumber = 1;
for (const file of filesToCopy) {
const newFilename = `${fileNumber}${path.extname(file)}`;
const targetPath = path.join(targetDir, newFilename);
await fs.copyFile(file, targetPath);
console.log(`Copied ${file} to ${targetPath}`);
fileNumber++;
}

console.log('All files have been copied successfully.');
} catch (err) {
console.error('An error occurred:', err);
}
}

const sourceDirectory = 'xxx'; // Replace with your source directory path
const targetDirectory = 'xxx'; // Replace with your target directory path

copyFilesWithNumberedNames(sourceDirectory, targetDirectory);