Загрузите файл, используя Electron и Node.js с Jquery - PullRequest
0 голосов
/ 31 января 2020

Я новичок в мире Electron, и для того, чтобы помочь с обучением, я создал приложение, которое после открытия автоматически загрузит zip-файл, именно в этот момент у меня возникают проблемы с тем, чтобы приложение работало, что должно произойдет, если файл загрузится и покажет прогресс, обновив в моем индексе индикатор выполнения bootstrap. html file Это небольшое приложение, поэтому у меня есть только два файла: main. js и index. html.

Мой главный. js код:


const {app, BrowserWindow, shell} = require('electron');
const fs = require('fs-extra');
const extract = require('extract-zip');
const child = require('child_process').exec;
global.jQuery = require('jquery');

let win
let downloadFolder = app.getPath("temp")
let cloudbarsinstallstaging = downloadFolder +"\\cloudbarsinstaller";

if (!fs.existsSync(cloudbarsinstallstaging)){
    fs.mkdirSync(cloudbarsinstallstaging);
}

function createWindow () {
    win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        },
    })

    win.loadFile('index.html')

    //single file download
    win.webContents.session.on('will-download', (event, item, webContents) => {
        //win.loadURL(`file://Z://Testing/Distributable.zip`);
        item.getFilename('file://Z://Testing/Distributable.zip')
        global.jQuery = require('jquery');
        // Set the save path, making Electron not to prompt a save dialog.
        item.setSavePath(cloudbarsinstallstaging + "\\Distributable.zip")

        item.on('updated', (event, state, progressBar) => {

          if (state === 'interrupted') {
            console.log('Download is interrupted but can be resumed')
          } else if (state === 'progressing') {
            if (item.isPaused()) {
              console.log('Download is paused')
            } else {

                let jQueryprogress = jQuery(".progress");
                let jQuerybar = jQuery(".progress-bar");
                let percent = 0;
                let update;
                let timer; 

                update = function(){
                    timer = setTimeout(function() {
                        console.log('Running');

                        try {
                            let percentage = item.getReceivedBytes()/item.getTotalBytes();
                            percent = percentage * 100;
                            percent = parseFloat(percent.toFixed(2));
                        } catch (error){
                            clearTimeout(timer);
                            console.log('Error while try to calculate bytes inside downloader'+ error);
                            percent = 100;
                            jQuerybar.css('width', '100%');
                            percent = 0;
                        }
                        speed = Math.floor(Math.random() * 100);
                        jQuerybar.css({width: percent + "%"});
                    }, speed);
                };

                jQuery('.progress').show();
                update(); 

              console.log(`Received bytes: ${item.getReceivedBytes()}`)
            }
          }
        })
        item.once('done', (event, state) => {
          if (state === 'completed') {
               console.log('Download successfully')
               console.log('Extracting Distributable')
               extract(cloudbarsinstallstaging + "\\Distributable.zip", {dir: cloudbarsinstallstaging}, function(err){
                   //code to handle errror
                   console.log('Extraction Completed')

                   console.log('now running installer')
                   var appinstaller = cloudbarsinstallstaging +"\\appInstaller.exe"
                child(appinstaller, function(err, data) {
                    if(err){
                       console.error(err);
                       return;
                    }

                    console.log(data.toString());
                });
               })
          } else {
            console.log(`Download failed: ${state}`)
            console.log(downloadFolder)
          }
        })
    })

    //open dev tools
    //win.webContents.openDevTools()

    //emitted when the window is closed
    win.on('closed', () => {
        win = null
    });
}

app.on('ready', createWindow)

//quite when all windows are closed
app.on('window-all-closed', () => {
    if(process.platform !== 'darwin'){
        app.quit()
    }
})

app.on('active', () => {
    if (win === null){
        createWindow()
    }
})

//this file can contain rest of your apps specfic main process code
//can also put them in seperate files and include them

Мой индекс. html код:


<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="./bootstrap/bootstrap.css" />

    <!-- Bootstrap Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->

  </head>
  <body>

    <h1>Welcome to the CloudBars Installer</h1>
    <p>Hang tight whilst we download and prepare the installer for...</p>

    <div class="progress">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
    </div>

    <button id="btn-dl">Download</button>
    We are using node <script>document.write(process.versions.node)</script>,
    chrome <script>document.write(process.versions.chrome)</script>,
    and electron <script>document.write(process.versions.electron)</script>.


    <script>
        window.nodeRequire = require;
        delete window.require;
        delete window.exports;
        delete window.module;
        </script>
        <script>
            let $ = require('jquery');
            </script>
            <script>
            require('popper.js');
            </script>
            <script>
            require('bootstrap');
            </script>

         <script>
         var handle = 0;
    function Download() {
        window.location.href = 'file://Z://Testing/Distributable.zip';
        clearInterval(handle);
    }
    $(document).ready(function () {
        handle = setTimeout(Download, 2000);            
    });
        </script>
         <!-- <script> document.location.href = 'file://Z://Testing/Distributable.zip'; </script> -->

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...