0

I am trying to open and save text files using electron. I am following this tutorial: https://ourcodeworld.com/articles/read/106/how-to-choose-read-save-delete-or-create-a-file-with-electron-framework

Here is the code I am using:

<!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>

Here is a gif of what's happening: https://media.giphy.com/media/Qf5rwE9eNjRtWb6m02/giphy.gif

Whenever I click the buttons to choose a file, I am able to click it but nothing else happens. It will not let me choose a file to open. Why is this happening?

fredjohnson
  • 187
  • 2
  • 10
  • 18
  • 1
    change the input type to `file` instead of `button`; check this [html input type="file"](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) – Sphinx Feb 16 '18 at 22:14

2 Answers2

0

As the document describes for input type="file":

<input> elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using form submission, or manipulated using JavaScript code and the File API.

Updated input type to file then put into the jsfiddle, it works.

PS: I kept the Javascript codes same as yours, so it will throw out some exceptions in the jsfiddle.

<!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="file" 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="file" 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>
Sphinx
  • 10,519
  • 2
  • 27
  • 45
  • Hi, I tried to run your code, I am able to choose a file, however it will not let me update the files contents in the input field, nor will it let me delete the file using the delete button. Thanks for your helping me open files though! – fredjohnson Feb 16 '18 at 22:28
  • That is another story which you didn't mention in your question. Some hints for new pains: 'delete' will be easy, you can just set the input value to empty string. 'edit' will be complicated based on your requirements. You can check this URL to learn how to read file first. [How to read a local text file?](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file) – Sphinx Feb 16 '18 at 22:35
0

dialog.showOpenDialog() uses an object literal for configuration. As an example, to filter only files to only allow text files, or to configure how the dialog behaves. You didn't say what platform you are one, but try this to see if it works. It it does, you are likely using windows and you must give it either 'openFile' or 'openDirectory' but not both.

Try to send a properties array with ['openFile']. Test this assertion with this:

console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']}))
Tim
  • 7,746
  • 3
  • 49
  • 83
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31