Electron 批量重命名工具代码示例,可以批量重命名文件夹中的所有文件:
const { app, BrowserWindow, dialog } = require('electron');
const fs = require('fs');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadFile('index.html');
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
// 选择文件夹
function selectDir() {
dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
}).then(result => {
if (!result.canceled) {
mainWindow.webContents.send('dir-selected', result.filePaths[0]);
}
})
}
// 重命名文件夹中所有文件
function renameFiles(dirPath, prefix, suffix) {
fs.readdir(dirPath, (err, files) => {
if (err) throw err;
files.forEach((file, i) => {
const oldPath = path.join(dirPath, file);
const ext = path.extname(oldPath);
const newName = `${prefix}${i + 1}${suffix}${ext}`;
const newPath = path.join(dirPath, newName);
fs.rename(oldPath, newPath, (err) => {
if (err) throw err;
});
});
});
}
// 主进程监听渲染进程触发的事件
const { ipcMain } = require('electron');
ipcMain.on('select-dir', () => {
selectDir();
});
ipcMain.on('rename-files', (event, args) => {
const { dirPath, prefix, suffix } = args;
renameFiles(dirPath, prefix, suffix);
event.reply('rename-complete');
});
在 index.html 文件中,你可以加入以下代码,来触发主进程中的事件:
<form id="rename-form">
<label for="dir-path">选择文件夹:</label>
<button id="select-dir">选择</button>
<br>
<input type="text" id="prefix" placeholder="前缀">
<input type="text" id="suffix" placeholder="后缀">
<br>
<button type="submit">重命名</button>
</form>
<script>
const { ipcRenderer } = require('electron');
document.getElementById('select-dir').addEventListener('click', (event) => {
event.preventDefault();
ipcRenderer.send('select-dir');
});
document.getElementById('rename-form').addEventListener('submit', (event) => {
event.preventDefault();
const form = event.target;
const dirPath = form.querySelector('#dir-path').value;
const prefix = form.querySelector('#prefix').value;
const suffix = form.querySelector('#suffix').value;
ipcRenderer.send('rename-files', { dirPath, prefix, suffix });
});
ipcRenderer.on('dir-selected', (event, arg) => {
const input = document.getElementById('dir-path');
input.value = arg;
});
ipcRenderer.on('rename-complete', () => {
alert('重命名完成');
});
</script>
还可以添加批量重命名文件名中的某些字符、前缀或后缀等高级功能
你可以根据自己的需求来修改和扩展