Electron Framework로 파일을 선택, 읽기, 저장, 삭제 또는 생성하는 방법

파일 수명주기 (CRUD)를 처리하기 위해 대화 상자  파일 시스템 구성 요소를 사용합니다 .

대화 모듈은 파일 열기 또는 경고와 같은 기본 시스템 대화 상자를 표시하는 API를 제공하므로 웹 응용 프로그램은 기본 응용 프로그램 및 Node.js 파일 시스템과 동일한 사용자 경험을 제공 할 수 있습니다.

필수 종속성로드

운영 시스템 대화 상자를 포함하여 저장, 열기 삭제 등으로 수행하려는 작업을 실행하려면 다음 종속성을로드해야합니다.

var remote = require('remote'); // Load remote compnent that contains the dialog dependency
var dialog = remote.require('dialog'); // Load the dialogs component of the OS
var fs = require('fs'); // Load the File System to execute our common tasks (CRUD)

 

노트

최신 버전의 Electron (> = 1)에서 다음 스 니펫을 사용하여 대화 상자에 액세스하십시오.

var app = require('electron').remote; var dialog = app.dialog;

// Or with ECMAScript 6 const {dialog} = require('electron').remote;

파일 만들기

파일을 만들려면 파일 시스템 을 사용 하고이 경우 시스템 의 기본 파일 저장 대화 상자 (경로를 검색)를 사용합니다. 당신이 사용할 수있는 

 

let content = "Some text to save into the file";

// You can obviously give a direct path without use the dialog (C:/Program Files/path/myfileexample.txt)
dialog.showSaveDialog((fileName) => {
    if (fileName === undefined){
        console.log("You didn't save the file");
        return;
    }

    // fileName is a string that contains the path and filename created in the save file dialog.  
    fs.writeFile(fileName, content, (err) => {
        if(err){
            alert("An error ocurred creating the file "+ err.message)
        }
                    
        alert("The file has been succesfully saved");
    });
}); 

 

파일 내용 읽기

파일 경로를 읽으려면 파일 시스템과 기본 파일 읽기 대화 상자를 사용합니다.

 

dialog.showOpenDialog((fileNames) => {
    // fileNames is an array that contains all the selected
    if(fileNames === undefined){
        console.log("No file selected");
        return;
    }

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

        // Change how to handle the file content
        console.log("The file content is : " + data);
    });
});
 

// Note that the previous example will handle only 1 file, if you want that the dialog accepts multiple files, then change the settings:
// And obviously , loop through the fileNames and read every file manually
dialog.showOpenDialog({ 
    properties: [ 
        'openFile', 'multiSelections', (fileNames) => {
            console.log(fileNames);
        }
    ]
});

 

기존 파일 내용 업데이트

기존 파일을 업데이트하려면 다음 코드를 사용하여 파일 경로 만 필요합니다 (파일 대화 상자로 다시 원하는 경우 검색하거나 이전에 저장된 파일 경로를 사용할 수 있음).

var filepath = "C:/Previous-filepath/existinfile.txt";// you need to save the filepath when you open the file to update without use the filechooser dialog againg
var content = "This is the new content of the file";

fs.writeFile(filepath, content, (err) => {
    if (err) {
        alert("An error ocurred updating the file" + err.message);
        console.log(err);
        return;
    }

    alert("The file has been succesfully saved");
});

파일 삭제

파일을 삭제하려면 파일 경로 만 있으면 존재하고 연결 해제 방법을 사용해야합니다. 존재하는 메소드는 파일이 존재하는지 점검 한 후 unlink 메소드로 파일을 삭제하도록 진행합니다.

var filepath = "C:/Path-toFile/file.txt";// Previously saved path somewhere

if (fs.existsSync(filepath)) {
    fs.unlink(filepath, (err) => {
        if (err) {
            alert("An error ocurred updating the file" + err.message);
            console.log(err);
            return;
        }
        console.log("File succesfully deleted");
    });
} else {
    alert("This file doesn't exist, cannot delete");
}

폴더 선택

폴더 경로를 검색하기 위해 대화 상자가있는 폴더를 선택할 수 있습니다.

dialog.showOpenDialog({
    title:"Select a folder",
    properties: ["openDirectory"]
}, (folderPaths) => {
    // folderPaths is an array that contains all the selected paths
    if(fileNames === undefined){
        console.log("No destination folder selected");
        return;
    }else{
        console.log(folderPaths);
    }
});

완전한 작업 예

다음 html 파일은 파일 시스템의 작동 방식을 이해하기 위해 프로젝트에서 테스트하는 데 사용할 수 있습니다. 코드는 간단한 crud UI를 생성합니다.

<!DOCTYPE html>
<html>
    <head>
        <title>Our Code World</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>
            <div style="text-align:center;">
                <input type="text" placeholder="Please select a file" id="actual-file" disabled="disabled"/>
                <input type="button" value="Choose a file" id="select-file"/>
            </div>
            <br><br>
            <textarea id="content-editor" rows="5"></textarea><br><br>
            <input type="button" id="save-changes" value="Save changes"/>
            <input type="button" id="delete-file" value="Delete file"/>
        </div>
        <hr>
        <div style="text-align:center;">
            <p>
                The file content will be the same as the editor.
            </p>
            <input type="button" value="Choose a file" id="create-new-file"/>
        </div>
        <script>
            var remote = require('remote'); 
            var dialog = remote.require('dialog');
            var fs = require('fs');
                
            document.getElementById('select-file').addEventListener('click',function(){
                dialog.showOpenDialog(function (fileNames) {
                    if(fileNames === undefined){
                        console.log("No file selected");
                    }else{
                        document.getElementById("actual-file").value = fileNames[0];
                        readFile(fileNames[0]);
                    }
                }); 
            },false);
            
            document.getElementById('save-changes').addEventListener('click',function(){
                var actualFilePath = document.getElementById("actual-file").value;
                
                if(actualFilePath){
                    saveChanges(actualFilePath,document.getElementById('content-editor').value);
                }else{
                    alert("Please select a file first");
                }
            },false);
            
            document.getElementById('delete-file').addEventListener('click',function(){
                var actualFilePath = document.getElementById("actual-file").value;
                
                if(actualFilePath){
                    deleteFile(actualFilePath);
                    document.getElementById("actual-file").value = "";
                    document.getElementById("content-editor").value = "";
                }else{
                    alert("Please select a file first");
                }
            },false);
            
            document.getElementById('create-new-file').addEventListener('click',function(){
                var content = document.getElementById("content-editor").value;
                
                dialog.showSaveDialog(function (fileName) {
                    if (fileName === undefined){
                        console.log("You didn't save the file");
                        return;
                    }
                    
                    fs.writeFile(fileName, content, function (err) {
                        if(err){
                            alert("An error ocurred creating the file "+ err.message)
                        }
                        
                        alert("The file has been succesfully saved");
                    });
                }); 
            },false);
            
            function readFile(filepath) {
                fs.readFile(filepath, 'utf-8', function (err, data) {
                    if(err){
                        alert("An error ocurred reading the file :" + err.message);
                        return;
                    }
                    
                    document.getElementById("content-editor").value = data;
                });
            }
            
            function deleteFile(filepath){
                fs.exists(filepath, function(exists) {
                    if(exists) {
                        // File exists deletings
                        fs.unlink(filepath,function(err){
                            if(err){
                                alert("An error ocurred updating the file"+ err.message);
                                console.log(err);
                                return;
                            }
                        });
                    } else {
                        alert("This file doesn't exist, cannot delete");
                    }
                });
            }
            
            function saveChanges(filepath,content){
                fs.writeFile(filepath, content, function (err) {
                    if(err){
                        alert("An error ocurred updating the file"+ err.message);
                        console.log(err);
                        return;
                    }
                    
                    alert("The file has been succesfully saved");
                }); 
            }
        </script>
    </body>
</html>

 

출처: https://ourcodeworld.com/articles/read/106/how-to-choose-read-save-delete-or-create-a-file-with-electron-framework

 

How to choose , read, save, delete or create a file with Electron Framework

Learn how to handle the lifecycle of a file with Electron.

ourcodeworld.com

 

'Electron' 카테고리의 다른 글

Electron Dialog !  (2) 2019.09.09
Electron 이란 !  (0) 2019.09.09

+ Recent posts