1 回答

TA貢獻(xiàn)1798條經(jīng)驗 獲得超7個贊
您遇到的問題是由 Electron 的 UI 函數(shù)的異步性質(zhì)引起的:它們不采用回調(diào)函數(shù),而是返回承諾。因此,您不必傳入回調(diào)函數(shù),而是處理 Promise 的解析。請注意,這僅適用于 Electron >= 版本 6。但是,如果您運(yùn)行舊版本的 Electron,您的代碼將是正確的 - 但您應(yīng)該真正更新到較新的版本(Electron v6 已發(fā)布一年多前) 。
像下面這樣調(diào)整您的代碼可以作為解決您的問題的起點。但是,由于您沒有說明如何生成哈希(來自哪里hash.createHash
?;您是否忘記聲明/導(dǎo)入hash
?;您是否忘記傳遞任何消息字符串?;您是否用作NodeJS模塊hash
的別名?)?crypto
,(此時)不可能調(diào)試為什么你沒有得到任何輸出console.log (filename)
(我假設(shè)你的意思是“在代碼中,不會創(chuàng)建隨機(jī)文件名”)。一旦您提供有關(guān)此問題的更多詳細(xì)信息,我很樂意相應(yīng)地更新此答案。
至于默認(rèn)文件名:根據(jù)Electron 文檔,您可以傳遞一個文件路徑來dialog.showSaveDialog ()
為用戶提供默認(rèn)文件名。
您正在使用的文件類型擴(kuò)展名實際上也應(yīng)該與文件擴(kuò)展名一起傳遞到保存對話框中。此外,將此文件擴(kuò)展名作為過濾器傳遞到對話框中將阻止用戶選擇任何其他文件類型,這最終也是您當(dāng)前通過將其附加到文件名來執(zhí)行的操作。
另外,您可以利用 CryptoJS 來生成文件名:給定一些任意字符串(實際上可能是隨機(jī)字節(jié)),您可以這樣做:filename = CryptoJS.MD5 ('some text here') + '.mfs';
但是,請記住明智地選擇輸入字符串。MD5 已被破解,因此不應(yīng)再用于存儲機(jī)密 — 使用任何對您存儲的文件加密至關(guān)重要的已知信息(例如 )本質(zhì)上data.password
是不安全的。
考慮到所有這些問題,最終可能會得到以下代碼:
const downloadPath = app.getPath('downloads'),
? ? ? path = require('path');
ipcMain.on('encryptFiles', (event, data) => {
? let output = [];
? const password = data.password;
? data.files.forEach((file) => {
? ? const buffer = fs.readFileSync(file.path);
? ? const dataURI = dauria.getBase64DataURI(buffer, file.type);
? ? const encrypted = CryptoJS.AES.encrypt(dataURI, password).toString();
? ? output.push(encrypted);
? })
? // not working:
? // const filename = hash.createHash('md5').toString('hex') + '.mfs';
? // alternative requiring more research on your end
? const filename = CryptoJS.MD5('replace me with some random bytes') + '.mfs';
? console.log(filename);
? const response = output.join(' :: ');
? dialog.showSaveDialog(
? ? {
? ? ? title: 'Save encrypted file',
? ? ? defaultPath: path.format ({ dir: downloadPath, base: filename }), // construct a proper path
? ? ? filters: [{ name: 'Encrypted File (*.mfs)', extensions: ['mfs'] }] // filter the possible files
? ? }
? ).then ((result) => {
? ? if (result.canceled) return; // discard the result altogether; user has clicked "cancel"
? ? else {
? ? ? var filePath = result.filePath;
? ? ? if (!filePath.endsWith('.mfs')) {
? ? ? ? // This is an additional safety check which should not actually trigger.
? ? ? ? // However, generally appending a file extension to a filename is not a
? ? ? ? // good idea, as they would be (possibly) doubled without this check.
? ? ? ? filePath += '.mfs';
? ? ? }
? ? ? fs.writeFile(filePath, response, (err) => console.log(err) )??
? ? }
? }).catch ((err) => {
? ? console.log (err);
? });
})
添加回答
舉報