elektron.JS [Notatnik]

Plik index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Notatnik</title>
</head>
<body>
  <textarea id="textArea" rows="10" cols="50"></textarea>
  <button id="saveButton">Zapisz</button>

  <script>
    const { ipcRenderer } = require('electron');

    document.getElementById('saveButton').addEventListener('click', () => {
      const textArea = document.getElementById('textArea');
      ipcRenderer.send('save-file', textArea.value);
    });
  </script>
</body>
</html>

const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const fs = require('fs');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  mainWindow.loadFile('index.html');
}

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.on('save-file', (event, content) => {
  dialog.showSaveDialog(mainWindow, {
    title: 'Zapisz plik',
    defaultPath: 'untitled.txt',
    filters: [{ name: 'Pliki tekstowe', extensions: ['txt'] }]
  }).then(result => {
    if (!result.canceled) {
      fs.writeFile(result.filePath, content, err => {
        if (err) {
          console.error('Błąd podczas zapisywania pliku:', err);
        }
      });
    }
  });
});