本地文件重命名
import fs from 'node:fs';import path from 'node:path';function* traverseDirectory(dirPath) {const dirEntries = fs.readdirSync(dirPath, { withFileTypes: true });dirEntries.sort((a, b) => a.name.localeCompare(b.name, 'en'));for (const dirEntry of dirEntries) {const fileName = dirEntry.name;const pathName = path.join(dirPath, fileName);if (dirEntry.isDirectory()) {yield* traverseDirectory(pathName);}else {yield pathName;}}}for (const filePath of traverseDirectory('temp')) {const ext = path.extname(filePath).slice(1);if (ext === 'js') {fs.rename(filePath, filePath.replace(/.js/, '.ts'), (err) => {if (err) throw err;console.log(filePath + ' rename complete');});}}
输入目录名称,递归遍历文件,使用 generator 来返回为文件的路径名,并使用 fs.rename 来对文件进行重命名。
