electron文件缓存
# 缓存文件
import { session } from 'electron'
import fs from 'fs'
import electronStore from 'electron-store'
const path = require('path')
const crypto = require('crypto')
const request = require('request')
const store = new electronStore()
// 设置缓存文件夹
const TEMP_PATH = 'temp'
// 设置文件夹位置(在安装应用文件夹内)
const basePath = path.join(app.getPath('userData'), TEMP_PATH)
// 创建缓存目录
fs.mkdir(basePath, { recursive: true }, err => {
if (err) console.warn(`mkdir path: ${basePath} err`)
})
const filter = {
urls: ['https://baidu.com/*', '*://baidu.com/*']
}
session.defaultSession.webRequest.onCompleted(filter, (details) => {
// 请求地址
const sourceUrl = details.url
// 只缓存视频
if(!sourceUrl.includes('.mp4')){
return
}
const name = crypto.createHash('md5').update(sourceUrl).digest('hex')
const filename = name + '.mp4'
const req = request({method:'get', uri: sourceUrl})
req.pipe(fs.createWriteStream(path.join(basePath, filename)))
var total = 0
req.on('response', (data) => {
total = parseInt(data.headers['content-length'])
console.log('response:', total)
})
req.on('data', (chunk) => {
console.log('data:', chunk)
})
req.on('error', (error) => {
console.warn('error:', error)
})
req.on('end', () => {
// 获取存储成功后本地路径
let localPath = path.join(basePath, filename)
if (process.platform !== 'darwin') { // 这里判断是否为windows系统,windows系统需要//这种反斜杠才能展示
const arr = localPath.split(path.sep)
localPath = arr.reduce((pre, cue) => {return pre ? `${pre}//${cue}` : cue}, '')
}
console.log('end: ',localPath)
store.set(name, localPath)
})
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 获取地址
//background.js
// 获取url地址
ipcMain.on('getUrl', async function(event, data){
const url = store.get(crypto.createHash('md5').update(data).digest('hex')) || data
event.sender.send('getUrlSuccess', url)
})
1
2
3
4
5
6
2
3
4
5
6
// renderer
ipcRenderer.on('getUrlSuccess', (event, data) => {
console.log('视频缓存地址:', data)
})
1
2
3
4
2
3
4
# 使用 electron-store 来保存数据
npm install electron-store
const Store = require('electron-store');
const store = new Store();
//set设置值
store.set('unicorn', 'wangyang');
console.log(store.get('unicorn'));
//=> 'wangyang'
// 使用点表示法访问嵌套属性
store.set('foo.bar', true);
//get取值
console.log(store.get('foo'));
//=> {bar: true}
//delete删除值
store.delete('unicorn');
console.log(store.get('unicorn'));
//=> undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2023/09/22, 16:54:32