Получить путь к созданному файлу из SaveFileDialog в электронном виде - PullRequest
0 голосов
/ 18 декабря 2018

Я пытаюсь сохранить путь к моему созданному файлу после использования SaveFileDialog, вот мой код:

    let path;
    dialog.showSaveDialog((fileName) => {
        if (fileName === undefined){
            console.log("You didn't save the file");
            return;
        }

        fs.writeFile(fileName, text, (err) => {
            if(err){
                alert("An error ocurred creating the file "+ err.message)
            }
            alert("The file has been succesfully saved");
        });
    }); 

Я хочу, чтобы после того, как пользователь создал файл, он вводил путь к файлу впеременный путь, это вообще возможно?

Ответы [ 2 ]

0 голосов
/ 18 декабря 2018

вы можете использовать версию синхронизации dialog.showSaveDialog.с синхронизированной версией вам не нужно объявлять переменную пути без инициализации

   let path = dialog.showSaveDialog( {
        title: "Save file",
        filters: [ { name:"png pictures", ext: [ "png" ] } ], // what kind of files do you want to see when this box is opend
        defaultPath: app.getPath("document") // the default path to save file
    });

    if ( ! path ) {
        // path is undefined
        return;
    }

    fs.writeFile( path , text , ( err , buf ) => {
        if ( err )
            return alert("saved");
        return alert("not saved");
    });

или асинхронной версии

  dialog.showSaveDialog( {
        title: "Save file",
        filters: [ { name:"png pictures", ext: [ "png" ] } ], // what kind of files do you want to see when this box is opend, ( users will be able to save this kind of files )
        defaultPath: app.getPath("document") // the default path to save file
    }, ( filePath ) => {
        if ( ! filePath ) {
            // nothing was pressed
            return;
        }

        path = filePath;
        fs.writeFile( path , text , ( err , buf ) => {
            if ( err )
                return alert("saved");
            return alert("not saved");
        });
    });
0 голосов
/ 18 декабря 2018

Вы почти у цели.Вам нужно дождаться результата диалога через обратный вызов.Проверьте документы .

Так что-то вроде:

let path; 

function saveProjectAs(text) {
    var options = {
        title: "Save project as ",
        message: "Save project as ",
        nameFieldLabel: "Project Name:",
        // defaultPath:  directory to show (optional)
    }

    dialog.showSaveDialog(mainWindow, options, saveProjectAsCallback);

    function saveProjectAsCallback(filePath) {
        // if user pressed "cancel" then `filePath` will be null
        if (filePath) {
         // check for extension; optional. upath is a node package.
            if (upath.toUnix(upath.extname(filePath)).toLowerCase() != ".json") {
                filePath = filePath + ".json"
            }

        path = filePath;

        fs.writeFile(path, text, (err) => {
           if(err){
                alert("An error ocurred creating the file "+ err.message)
            }
           alert("The file has been succesfully saved");
         });

        }
    }
}
...