const fs = require('fs') const path = require('path') import { ElectronDownloadManager } from 'electron-dl-manager'; const manager = new ElectronDownloadManager(); export default async function ({ app, shell, BrowserWindow, ipcMain }) { const userDataPath = app.getPath('userData') //默认浏览器打开url ipcMain.on('open-url-browser', (e, url) => { shell.openPath(url) }) //使用默认应用打开本地文件 ipcMain.on('open-path-app', (e, path) => { shell.openExternal(path) }) //复制文件 ipcMain.on('copy-file-default', (e, { source, destination }) => { copyFile(source, destination, (error, filePath) => { e.reply('copy-file-default-reply', { error, filePath }) }) }) //下载文件 ipcMain.on('download-file-default', (e,url) => { createFolder('selfFile').then(async ()=>{ const browserWindow = BrowserWindow.fromId(e.sender.id) const id = await manager.download({ window: browserWindow, url: url, directory: userDataPath + '/selfFile/', callbacks: { onDownloadStarted: async ({ id, item, webContents }) => { // Do something with the download id }, onDownloadProgress: async ({ id, item, percentCompleted }) => { browserWindow.webContents.invoke('download-progress', { id, percentCompleted, // Get the number of bytes received so far bytesReceived: item.getReceivedBytes(), }); }, onDownloadCompleted: async ({ id, item }) => { console.log(item) }, onDownloadCancelled: async () => {}, onDownloadInterrupted: async () => {}, onError: (err, data) => {}, } }); }) }) function copyFile(source, destination, callback) { let path = userDataPath + '\\selfFile\\' + destination createFolder('selfFile').then(() => { const readStream = fs.createReadStream(source) const writeStream = fs.createWriteStream(path) readStream.on('error', (error) => { callback(error, null) }) writeStream.on('error', (error) => { callback(error, null) }) writeStream.on('close', () => { callback(null, path) }) readStream.pipe(writeStream) }) } function createFolder(folderName) { return new Promise((resolve, reject) => { const folderPath = path.join(userDataPath, folderName) // 异步检查文件夹是否存在,不存在则创建 fs.access(folderPath, fs.constants.F_OK, (err) => { if (err) { fs.mkdir(folderPath, { recursive: true }, (mkdirErr) => { if (mkdirErr) { console.error(mkdirErr) reject() } else { console.log(`Folder ${folderName} created successfully.`) resolve() } }) } else { console.log(`Folder ${folderName} already exists.`) resolve() } }) }) } }