本文概述
为了处理文件(CRUD)的生命周期, 我们将使用对话框和文件系统组件。
对话框模块提供了用于显示本机系统对话框(例如打开文件或警报)的API, 因此Web应用程序可以提供与本机应用程序和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");
});
});