1 Star 0 Fork 0

sangong/translateFiles

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
listFiles.js 2.86 KB
一键复制 编辑 原始数据 按行查看 历史
sangong 提交于 2024-06-18 10:03 +08:00 . update listFiles.js.
const fs = require('fs');
const path = require('path');
const { pinyin } = require('pinyin-pro');
// 获取当前目录
const currentDirectory = __dirname;
// 将中文名称转换为拼音
function toPinyin(name) {
return pinyin(name, { toneType: 'none', type: 'array' }).join('');
}
// 递归读取目录
function readDirectory(directory) {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, items) => {
if (err) {
return reject(err);
}
let results = [];
let promises = items.map(item => {
const fullPath = path.join(directory, item);
const pinyinName = toPinyin(item);
const newFullPath = path.join(directory, pinyinName);
return new Promise((res, rej) => {
fs.stat(fullPath, (err, stats) => {
if (err) {
return rej(err);
}
const renamePromise = new Promise((renameRes, renameRej) => {
if (fullPath !== newFullPath) {
fs.rename(fullPath, newFullPath, (renameErr) => {
if (renameErr) {
return renameRej(renameErr);
}
renameRes();
});
} else {
renameRes();
}
});
renamePromise.then(() => {
if (stats.isDirectory()) {
readDirectory(newFullPath).then(subResults => {
results.push({
type: 'directory',
name: pinyinName,
path: newFullPath,
contents: subResults
});
res();
}).catch(rej);
} else {
results.push({
type: 'file',
name: pinyinName,
path: newFullPath
});
res();
}
}).catch(rej);
});
});
});
Promise.all(promises).then(() => resolve(results)).catch(reject);
});
});
}
readDirectory(currentDirectory).then(results => {
console.log(JSON.stringify(results, null, 2));
}).catch(err => {
console.error('Error reading directory:', err);
});
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sangonghappy/translate-files.git
git@gitee.com:sangonghappy/translate-files.git
sangonghappy
translate-files
translateFiles
master

搜索帮助