文件管理是桌面应用非常重要的功能,几乎所有的应用都会涉及到文件的内容。
安装依赖的库
**提示:**bower也是一个包管理,通过这个库你可以安装所有js和css的库。
安装boostrap
安装jquery
该章的内容是创建一个表单,输入相应的名字和Email,系统会将其保存在一个.txt文件当中,当你再次打开的时候会自动从该文件读取相应的内容。
我们需要创建一个main.js文件,并且输入下面所示的代码。
const {
app,
BrowserWindow
} = require('electron')
const url = require('url')
const path = require('path')
let win
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600
})
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}))
}
app.on('ready', createWindow)
同样的我们需要创建一个index.html,用来创建显示的内容。
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>File System</title>
<link rel = "stylesheet"
href = "./bower_components/bootstrap/dist/css/bootstrap.min.css" />
<style type = "text/css">
#contact-list {
height: 150px;
overflow-y: auto;
}
</style>
</head>
<body>
<div class = "container">
<h1>Enter Names and Email addresses of your contacts</h1>
<div class = "form-group">
<label for = "Name">Name</label>
<input type = "text" name = "Name" value = "" id = "Name"
placeholder = "Name" class = "form-control" required>
</div>
<div class = "form-group">
<label for = "Email">Email</label>
<input type = "email" name = "Email" value = "" id = "Email"
placeholder = "Email" class = "form-control" required>
</div>
<div class = "form-group">
<button class = "btn btn-primary" id = "add-to-list">Add to list!</button>
</div>
<div id = "contact-list">
<table class = "table-striped" id = "contact-table">
<tr>
<th class = "col-xs-2">S. No.</th>
<th class = "col-xs-4">Name</th>
<th class = "col-xs-6">Email</th>
</tr>
</table>
</div>
<script src = "./view.js" ></script>
</div>
</body>
</html>
现在 我们创建一个view.js文件。
我们创建一个函数loadAndDisplayContacts(),该函数在初始加载时会读取文件并且追加到列表当中,同时创建了一个单击事件,将当前的信息添加到列表当中。
let $ = require('jquery')
let fs = require('fs')
let filename = 'contacts'
let sno = 0
$('#add-to-list').on('click', () => {
let name = $('#Name').val()
let email = $('#Email').val()
fs.appendFile('contacts', name + ',' + email + '\n')
addEntry(name, email)
})
function addEntry(name, email) {
if(name && email) {
sno++
let updateString = '<tr><td>'+ sno + '</td><td>'+ name +'</td><td>'
+ email +'</td></tr>'
$('#contact-table').append(updateString)
}
}
function loadAndDisplayContacts() {
//Check if file exists
if(fs.existsSync(filename)) {
let data = fs.readFileSync(filename, 'utf8').split('\n')
data.forEach((contact, index) => {
let [ name, email ] = contact.split(',')
addEntry(name, email)
})
} else {
console.log("File Doesn\'t Exist. Creating new file.")
fs.writeFile(filename, '', (err) => {
if(err)
console.log(err)
})
}
}
loadAndDisplayContacts()
最终显示的效果