Как выбрать, прочитать, сохранить, удалить или создать файл с помощью 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);
}
]
});

Открыть файл диалога электрон

Обновить существующее содержимое файла

Чтобы обновить существующий файл, нам нужен только путь к файлу (вы можете получить его, если захотите снова с помощью filedialog или использовать ранее сохраненный путь к файлу), используя следующий код:

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 Electron


Our Code World

The file content will be the same as the editor.

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"); }); }

Повеселись !

Ссылка на основную публикацию
Adblock
detector