本文概述
- 加载所需的依赖项
- 建立档案
- 读取文件内容
- 更新现有文件内容
- 删除档案
- 选择一个文件夹
- 完整的工作示例
对话框模块提供了用于显示本机系统对话框(例如打开文件或警报)的API, 因此Web应用程序可以提供与本机应用程序和Node.js文件系统相同的用户体验。
加载所需的依赖项 【如何使用Electron Framework选择,读取,保存,删除或创建文件】我们需要加载以下依赖项, 以执行我们要完成的任务, 例如保存, 打开删除等, 包括” 操作系统” 对话框。
var remote = require('remote');
// Load remote compnent that contains the dialog dependencyvar dialog = remote.require('dialog');
// Load the dialogs component of the OSvar 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 6const {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 selectedif(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 contentconsole.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 manuallydialog.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 againgvar 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");
});
删除档案 要删除文件, 你只需要文件的路径并使用exist和unlink方法。 exist方法检查文件是否存在, 然后使用unlink方法删除该文件。
var filepath = "C:/Path-toFile/file.txt";
// Previously saved path somewhereif (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 pathsif(fileNames === undefined){console.log("No destination folder selected");
return;
}else{console.log(folderPaths);
}});
完整的工作示例 以下html文件可用于在你的项目中进行测试, 以了解文件系统的工作方式。该代码将生成一个简单的Crud UI。
文章图片
<
!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="http://www.srcmini.com/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="http://www.srcmini.com/Save changes"/>
<
input type="button" id="delete-file" value="http://www.srcmini.com/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="http://www.srcmini.com/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 = http://www.srcmini.com/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").valuehttp://www.srcmini.com/= "";
document.getElementById("content-editor").valuehttp://www.srcmini.com/= "";
}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 = http://www.srcmini.com/data;
});
}function deleteFile(filepath){fs.exists(filepath, function(exists) {if(exists) {// File exists deletingsfs.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>
玩得开心 !
推荐阅读
- 如何仅下载和使用Bootstrap 3 Grid样式
- 如何将JSON对象从Java返回到javascript(cordova)(2)
- SCRCPY(提供显示和控制USB上连接的Android设备的应用程序)
- Grommet(专为ReactJS设计的设计系统)
- Android Volley Self签名证书
- 如何在mybatis的mapper接口中为更新查询编写foreach循环
- Dockerized webapp - 热重新加载
- WebApplication ASP.Net C#。取消屏蔽文本框,也称为显示密码
- 解决Azure Web App 500内部服务器错误超时问题并对其进行故障排除