本地文件重命名

  1. import fs from 'node:fs';
  2. import path from 'node:path';
  3. function* traverseDirectory(dirPath) {
  4. const dirEntries = fs.readdirSync(dirPath, { withFileTypes: true });
  5. dirEntries.sort((a, b) => a.name.localeCompare(b.name, 'en'));
  6. for (const dirEntry of dirEntries) {
  7. const fileName = dirEntry.name;
  8. const pathName = path.join(dirPath, fileName);
  9. if (dirEntry.isDirectory()) {
  10. yield* traverseDirectory(pathName);
  11. }
  12. else {
  13. yield pathName;
  14. }
  15. }
  16. }
  17. for (const filePath of traverseDirectory('temp')) {
  18. const ext = path.extname(filePath).slice(1);
  19. if (ext === 'js') {
  20. fs.rename(filePath, filePath.replace(/.js/, '.ts'), (err) => {
  21. if (err) throw err;
  22. console.log(filePath + ' rename complete');
  23. });
  24. }
  25. }

输入目录名称,递归遍历文件,使用 generator 来返回为文件的路径名,并使用 fs.rename 来对文件进行重命名。