Electron 搭建文件浏览器
需要的模块
- electron
- electron-builder
- async
实现的功能
类似window系统中的文件夹
- 显示指定目录下的所有文件列表
- 区分文件和文件夹(最好区分每一种文件类型)
- 点击文件可以打开(默认打开方式),点击文件夹可以进入该文件目录
- 可以返回上一目录(返回到顶部时,直接关闭窗口)
- 可以通过快捷键或按钮直接打开当前目录的文件夹
功能1:获取指定目录下的文件列表
使用fs模块的readdir方法
const fs = require("fs");
fs.readdir(folderpath, (err, files) => {
if (err) {
throw new Error("Sorry, cannot load folder");
}
// 处理文件列表
})
功能2:区分文件列表中的文件和文件夹
使用fs模块的stat方法
// 在上面的 ‘处理文件列表’ 处,调用
fileSystem.inspectAndDescribeFiles(folderPath, files, (err, files) => {
if (err) {
alert("sorry, cannot display files")
return;
}
// 根据文件信息,显示文件列表
})
// 以下代码封装在fileSystem.js模块中
const async = require("async");
// 查看和描述文件列表
function inspectAndDescribeFiles(folderPath, files, cb) {
// 使用async模块调用异步方法并获取文件列表的详细数据
async.map(files, (file, asyncCB) => {
const resolveFilePath = path.resolve(folderPath, file);
inspectAndDescribeFile(resolveFilePath, asyncCB);
}, cb)
}
const fs = require('fs');
// 查看和描述文件
function inspectAndDescribeFile(filePath, cb) {
let result = {
file: path.basename(filePath),
path: filePath,
type: '',
modifyTime: 0,
size: 0
};
fs.stat(filePath, (err, stat) => {
if (err) {
cb(err);
} else {
if (stat.isFile()) {
// 描述文件
} else if (stat.idDirectory()) {
// 描述文件夹
}
cb(err, result);
}
})
}
功能3:点击页面上的文件和文件夹,打开文件或加载新的文件目录
- 对于文件,直接使用默认的打开方式打开
const shell = require("electron").shell;
shell.openPath(filePath);
- 对于文件夹,需要重走我们的 加载文件列表的方法 loadDirectory(file.path)
功能4:返回上一目录
- 需要记录文件目录路由,并使用 加载文件列表的方法 loadDirectory(file.path)
- 对于返回到顶层时,直接退出应用
const {app} = require("electron").remote;
app.exit(); // 退出程序
功能5:快捷键打开window系统的文件夹
配置index.js
// 创建浏览器窗口
const win = new BrowserWindow({
width: 1280,
height: 720,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true, // 增加此行,允许使用electron的remote模块
},
autoHideMenuBar: true, // 默认隐藏菜单栏
fullscreen: true, // 默认全屏
});
快捷键监听:
const {shell} = require("electron").remote;
function bindOpenFoldEvent() {
document.addEventListener("keyup", (e) => {
// console.log(e.keyCode); // 所按键的code
// console.log(e.ctrlKey); // 是否按了Ctrl键
// console.log(e.altKey); // 是否按了Alt键
if (e.keyCode == 82 && e.altKey) {
const currentFoldUrl = ".."; // 当前目录路径
shell.openPath(currentFoldUrl); // 打开当前目录
}
})
}
文件浏览器的demo: https://github.com/tugenhua0707/electron-demo/
分类:
杂项
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了