Electron 애플리케이션 초기 설정: 메인 프로세스 및 프리로드 스크립트 추가, HTML 인터페이스 구현, 디렉토리 선택 및 감시 기능 추가

This commit is contained in:
2024-12-16 23:08:23 +09:00
parent ea410d66f8
commit 776e2c9d82
6 changed files with 2278 additions and 16 deletions

48
index.html Normal file
View File

@@ -0,0 +1,48 @@
<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Directory Watcher App</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}
#selected-directory {
margin-top: 20px;
word-break: break-all;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>디렉토리 감시 애플리케이션</h1>
<button id="select-directory">디렉토리 선택</button>
<div id="selected-directory">선택된 디렉토리 없음</div>
<script>
const selectDirButton = document.getElementById('select-directory');
const selectedDirDiv = document.getElementById('selected-directory');
selectDirButton.addEventListener('click', async () => {
const result = await window.electronAPI.selectDirectory();
if (!result.canceled) {
selectedDirDiv.textContent = `선택된 디렉토리: ${ result.path }`;
} else {
selectedDirDiv.textContent = '디렉토리 선택이 취소되었습니다.';
}
});
</script>
</body>
</html>

148
main.js Normal file
View File

@@ -0,0 +1,148 @@
// main.js
const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const path = require("path");
const chokidar = require("chokidar");
const fs = require("fs").promises;
// 무시할 파일/디렉토리를 결정하는 함수
function shouldIgnore(itemName) {
const ignoredItems = [".git", "node_modules", ".env"];
return ignoredItems.includes(itemName);
}
// 파일 이름을 정규화하는 함수
async function normalizeFileName(filePath) {
const dir = path.dirname(filePath);
const oldName = path.basename(filePath);
const newName = oldName.normalize("NFC");
if (oldName !== newName && !shouldIgnore(oldName)) {
const newPath = path.join(dir, newName);
try {
await fs.rename(filePath, newPath);
console.log(`이름 변경: "${oldName}" -> "${newName}"`);
return newPath;
} catch (error) {
console.error(`이름 변경 실패 ("${oldName}"):`, error);
return filePath;
}
}
return filePath;
}
// 디렉토리를 재귀적으로 처리하는 함수
async function processDirectory(dirPath) {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
if (!shouldIgnore(entry.name)) {
await processDirectory(fullPath);
await normalizeFileName(fullPath);
}
} else {
await normalizeFileName(fullPath);
}
}
await normalizeFileName(dirPath);
} catch (error) {
console.error(`디렉토리 처리 중 오류 발생 ("${dirPath}"):`, error);
}
}
// 창을 생성하는 함수
function createWindow() {
const win = new BrowserWindow({
width: 600,
height: 400,
webPreferences: {
preload: path.join(__dirname, "preload.js"), // 보안상 추천
nodeIntegration: false,
contextIsolation: true,
},
});
win.loadFile("index.html");
// 개발자 도구 열기 (배포 시 제거 권장)
// win.webContents.openDevTools();
}
// 애플리케이션 준비 시 창 생성
app.whenReady().then(() => {
createWindow();
app.on("activate", function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// 모든 창이 닫히면 애플리케이션 종료
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
});
// 디렉토리 감시 로직 처리
ipcMain.handle("select-directory", async () => {
const result = await dialog.showOpenDialog({
properties: ["openDirectory"],
});
if (result.canceled) {
return { canceled: true };
} else {
const selectedPath = result.filePaths[0];
console.log(`선택된 디렉토리: ${selectedPath}`);
// 기존 감시자 종료 (필요 시)
if (global.watcher) {
global.watcher.close();
}
// 디렉토리 초기 처리
await processDirectory(selectedPath);
// 디렉토리 감시 시작
global.watcher = chokidar.watch(selectedPath, {
ignored: (pathStr) => {
const baseName = path.basename(pathStr);
return shouldIgnore(baseName);
},
persistent: true,
ignoreInitial: false,
awaitWriteFinish: {
stabilityThreshold: 200,
pollInterval: 100,
},
depth: Infinity,
});
global.watcher
.on("add", async (filePath) => {
console.log(`파일 추가됨: "${filePath}"`);
await normalizeFileName(filePath);
})
.on("change", async (filePath) => {
console.log(`파일 변경됨: "${filePath}"`);
await normalizeFileName(filePath);
})
.on("unlink", (filePath) => {
console.log(`파일 삭제됨: "${filePath}"`);
})
.on("addDir", async (dirPath) => {
console.log(`디렉토리 추가됨: "${dirPath}"`);
await processDirectory(dirPath);
})
.on("unlinkDir", (dirPath) => {
console.log(`디렉토리 삭제됨: "${dirPath}"`);
})
.on("error", (error) => console.error(`Watcher error: ${error}`))
.on("ready", () => {
console.log("초기 스캔 완료. 변경 감시 중...");
});
return { canceled: false, path: selectedPath };
}
});

View File

@@ -14,20 +14,15 @@ async function normalizeFileName(filePath) {
const oldName = path.basename(filePath); const oldName = path.basename(filePath);
const newName = oldName.normalize("NFC"); const newName = oldName.normalize("NFC");
// console.log(`정규화 시도: "${oldName}" -> "${newName}"`);
if (oldName !== newName && !shouldIgnore(oldName)) { if (oldName !== newName && !shouldIgnore(oldName)) {
const newPath = path.join(dir, newName); const newPath = path.join(dir, newName);
try { try {
await fs.rename(filePath, newPath); await fs.rename(filePath, newPath);
// console.log(`이름 변경 성공: "${oldName}" -> "${newName}"`);
return newPath; return newPath;
} catch (error) { } catch (error) {
console.error(`이름 변경 실패 ("${oldName}"):`, error); console.error(`이름 변경 실패 ("${oldName}"):`, error);
return filePath; return filePath;
} }
} else {
// console.log(`정규화 필요 없음: "${oldName}"`);
} }
return filePath; return filePath;
} }
@@ -40,7 +35,6 @@ async function processDirectory(dirPath) {
for (const entry of entries) { for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name); const fullPath = path.join(dirPath, entry.name);
// console.log(`파일 처리 시작: "${fullPath}"`);
if (entry.isDirectory()) { if (entry.isDirectory()) {
if (!shouldIgnore(entry.name)) { if (!shouldIgnore(entry.name)) {
await processDirectory(fullPath); await processDirectory(fullPath);
@@ -49,10 +43,8 @@ async function processDirectory(dirPath) {
} else { } else {
await normalizeFileName(fullPath); await normalizeFileName(fullPath);
} }
// console.log(`파일 처리 완료: "${fullPath}"`);
} }
await normalizeFileName(dirPath); await normalizeFileName(dirPath);
// console.log(`디렉토리 처리 완료: "${dirPath}"`);
} catch (error) { } catch (error) {
console.error(`디렉토리 처리 중 오류 발생 ("${dirPath}"):`, error); console.error(`디렉토리 처리 중 오류 발생 ("${dirPath}"):`, error);
} }

2063
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,26 @@
{ {
"name": "nfd2nfc", "name": "nfd2nfc",
"version": "1.0.0", "version": "1.0.0",
"main": "watcher.js", "main": "main.js",
"description": "Convert NFD to NFC", "description": "Convert NFD to NFC",
"dependencies": { "dependencies": {
"chokidar": "^4.0.1", "chokidar": "^4.0.1",
"electron": "^33.2.1",
"readdirp": "^4.0.2" "readdirp": "^4.0.2"
}, },
"devDependencies": {},
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "start": "electron .",
"start": "node watcher.js", "package": "electron-packager . NFD2NF --platform=darwin --arch=x64 --icon=build/icons/MacIcon.icns --overwrite --prune=true --out=dist",
"build": "pkg normalize.js --target node16-macos-x64,node16-linux-x64,node16-win-x64 --output NFD2NFC" "pkg": "pkg normalize.js --target node16-macos-x64,node16-linux-x64,node16-win-x64 --output ./dist/NFD2NFC"
},
"directories": {
"output": "dist",
"buildResources": "build"
}, },
"keywords": [], "keywords": [],
"author": "pieroot", "author": "pieroot",
"license": "MIT" "license": "MIT",
"devDependencies": {
"electron-packager": "^17.1.2"
}
} }

6
preload.js Normal file
View File

@@ -0,0 +1,6 @@
// preload.js
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
selectDirectory: () => ipcRenderer.invoke("select-directory"),
});