Electron

Electron, 시스템 다이얼로그(System Dialog)

iKay 2018. 12. 23. 21:05
반응형

0. 들어가며

데스크톱 애플리케이션을 구현할 때 시스템 다이얼로그(system dialog)는 필수이다. Electron은 파일을 읽고 저장하거나 어떤 상황을 알리기 위한 네이티브 시스템 다이얼로그를 dialog module로서 제공한다. 여러 시스템 다이얼로그가 있으나 그 중 'showOpenDialog' 를 이번 포스팅에 다뤄볼 예정이다. 그 외에, 'showSaveDialog', 'showMessageBox' 등의 메쏘드도 있으니 상황에 맞게 사용하면 될 것이다.   

 

1. showOpenDialog

showOpenDialog는 파일을 읽기 위해 사용되는 네이티브 시스템 다이얼로그이다. 간단한 예제로서 텍스트 파일을 읽어볼 것인데, project directory에 다음과 같이 'exampleText'라는 이름으로 텍트스 파일을 하나만들고 본문을 작성한 후 저장하자. 

 

 

 

 

 

그리고 'main.js'를 다음과 같이 작성하자. 지난 번에 다뤘던 ipc가 나오는데 짧게 다시 설명하자면, ipcMain.on('openFile', callback) 은 renderer로 부터 'openFile' 이라는 이름으로 ipc를 통해 메시지를 보내, 이벤트를 발생시는 것이다. callback 함수 안에서 dialog 모듈을 불러오고, showOpenDialog라는 method를 호출하는 것도 볼 수 있다. 즉, renderer로 부터 ipc를 통해 이벤트발생시 dialog를 띄우는 로직인 것이다. 

 

dialog를 띄운 후에는 텍스트 파일을 읽고, 텍스트 내용을 그대로 renderer로 보내준다. 여담이지만, 대용량의 파일을 읽는 것이라면 readFile을 사용하는 것 보다 stream을 사용하는 것이 메모리 사용 측면에서 볼 때 더 유리할 것이나, 이 부분은 오늘 다루는 주제의 범위에 벗어나므로 설명하지 않겠다. 

 

/* main.js */

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

let win;

function createWindow() {
  win = new BrowserWindow({width: 800, height: 600});
  /* load local .html file*/
  win.loadURL(`file://${__dirname}/index.html`);
}

ipcMain.on('openFile', (event, path) => {
  const {dialog} = require('electron');
  const fs = require('fs');
  dialog.showOpenDialog(function (fileNames) {

    // fileNames is an array that contains all the selected 
    if(fileNames === undefined) {
      console.log("No file selected"); 
    } else {
      readFile(fileNames[0]);
    }
  });

  function readFile(filepath) {
    fs.readFile(filepath, 'utf-8', (err, data) => {
      if(err){
        alert("An error ocurred reading the file :" + err.message);
        return;
      }

      // handle the file content 
      event.sender.send('fileData', data);
    });
  }
});

app.on('ready', createWindow);

 

 

이제 renderer 코드, index.html을 살펴보자. 프로세스 실행 후 renderer가 실행된 직 후 ipc를 통해 dialog를 띄우는 event를 발생시키고, 파일을 읽은 후 결과(텍스트)를 ipc를 통해 받는 부분이 구현돼있다. 참고로 간단히 alert() 함수도 사용할 수 있다.  

 

 

<!-- index.html -->
<body>
<script type = "text/javascript">
  alert('hello alert');
  const {ipcRenderer} = require('electron');
  ipcRenderer.send('openFile', () => {
    console.log("Event sent.");
  });

  ipcRenderer.on('fileData', (event, data) => {
    document.write(data);
  });
</script>
</body>

 

위와 같이 코드를 작성하고 electron을 실행시키자. 

 

$ electron main.js

 

 

그러면 다음과 같이 alert()창이 먼저 뜨고 확인을 누르면,

 

 

 

읽어 들일 파일을 선택하는 system dialog가 뜬다. exampleText를 선택해보자. 

 

 

 

그러면 아래 그림과 같이 방금 작성했던 텍스트가 renderer 화면에 출력돼 파일을 정상적으로 읽었음을 확인했다. 

 

 

2. 결론

파일을 읽는 시스템 다이얼로그(showOpenDialog)를 이번에 다뤄봤다. 데스트 톱 애플리케이션을 개발할 때 파일을 읽고 쓰는 것은 매우 중요하다. 따라서 위 내용을 잘 알고 넘어가는 것은 중요하다고 생각한다. 

 

시스템 다이얼로그 외에 웹 브라우저에서 흔히 사용되는 'alert'를 사용해도 되나 추천하지 않는 것 같다. 그 이유를 정확하게는 모르겠으나 찾아봐야 할 이유도 찾아볼 가치는 있는 것 같다.  

 

3. 소스코드

https://github.com/hgs0426/electron/tree/master/system_dialogs

 

 

4. 참고

[1] https://electronjs.org/docs/api/dialog

 

[2] https://www.tutorialspoint.com/electron/electron_system_dialogs.htm

반응형