Я пытаюсь сохранить путь к созданному файлу после использования 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");
});
});
Я хочу, чтобы после того, как пользователь создал файл, он ввел путь к файлу в переменной path, возможно ли это?
Вы почти там. Вам нужно дождаться результата диалога через обратный вызов. Проверьте документы.
Так что-то вроде:
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");
});
}
}
}
upath
. , ,
Вы можете использовать синхронизированную версию 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");
});
});