Electron / NodeJS和应用程序冻结setInterval / async代码

时间:2016-12-08 10:17:47

标签: node.js multithreading asynchronous electron

我正在开发一个electron应用程序,它使用电子api每3秒进行一次屏幕截图捕获,并将其写入给定的目标路径。我已经设置了一个单独的BrowserWindow,其中捕获代码运行(参见下面的代码结构)一个setInterval()“循环”,但每当捕获发生时,应用程序会冻结片刻。我认为文件source.thumbnail.toPng()中调用了writeScreenshot()ScreenCapturer.jshtml.js方法。

我设置了这个结构,虽然这是要走的路,但显然这不是。 WebWorkers也不会帮助我,因为我需要节点模块,如fs,path和desktopCapturer(来自电子)。

每次间隔代码(如文件ScreenCapturer.jshtml.js中所示)运行时,如何在不阻塞主线程的情况下执行此类任务(因为我认为渲染器进程是单独的进程?)

我的代码作为参考

main.js (主要流程)

// all the imports and other
// will only show the import that matters
import ScreenCapturer from './lib/capture/ScreenCapturer';  

app.on('ready', () => {
   // Where I spawn my main UI
   mainWindow = new BrowserWindow({...});
   mainWindow.loadURL(...);
   // Other startup stuff

   // Hee comes the part where I call function to start capturing
   initCapture();
});

function initCapture() {
    const sc = new ScreenCapturer();
    sc.startTakingScreenshots();
}

ScreenCapturer.js (主流程使用的模块)

'use strict';

/* ******************************************************************** */
/* IMPORTS */
import { app, BrowserWindow, ipcMain } from 'electron';
import url from 'url';
import path from 'path';
/* VARIABLES */
let rendererWindow;
/*/********************************************************************///
/*///*/

/* ******************************************************************** */
/* SCREENCAPTURER */
export default class ScreenCapturer {
    constructor() {
        rendererWindow = new BrowserWindow({
            show: true, width: 400, height: 600,
            'node-integration': true,
            webPreferences: {
                webSecurity: false
            }
        });                        
        rendererWindow.on('close', () => {
            rendererWindow = null;
        });
    }

    startTakingScreenshots(interval) {
        rendererWindow.webContents.on('did-finish-load', () => {
            rendererWindow.openDevTools();
            rendererWindow.webContents.send('capture-screenshot', path.join('e:', 'temp'));
        }); 
        rendererWindow.loadURL(
            url.format({
                pathname: path.join(__dirname, 'ScreenCapturer.jshtml.html'),
                protocol: 'file:',
                slashes: true
            })
        );                       
    }    
}
/*/********************************************************************///
/*///*/

ScreenCapturer.jshtml.js (在渲染器浏览器窗口中加载的thml文件)

<html>
    <body>
        <script>require('./ScreenCapturer.jshtml.js')</script>
    </body>
</html>

ScreenCapturer.jshtml.js (从渲染器进程中的html文件加载的js文件)

import { ipcRenderer, desktopCapturer, screen } from 'electron';
import path from 'path';
import fs from 'fs';
import moment from 'moment';
let mainSource;

function getMainSource(mainSource, desktopCapturer, screen, done) {
    if(mainSource === undefined) {
        const options = {
            types: ['screen'],
            thumbnailSize: screen.getPrimaryDisplay().workAreaSize
        };
        desktopCapturer.getSources(options, (err, sources) => {
            if (err) return console.log('Cannot capture screen:', err);
            const isMainSource = source => source.name === 'Entire screen' || source.name === 'Screen 1';
            done(sources.filter(isMainSource)[0]);        
        });
    } else {
        done(mainSource);
    }
}
function writeScreenshot(png, filePath) {
    fs.writeFile(filePath, png, err => {        
        if (err) { console.log('Cannot write file:', err); }
        return;       
    });
}

ipcRenderer.on('capture-screenshot', (evt, targetPath) => {    
    setInterval(() => {          
        getMainSource(mainSource, desktopCapturer, screen, source => {
            const png = source.thumbnail.toPng();
            const filePath = path.join(targetPath, `${moment().format('yyyyMMdd_HHmmss')}.png`);
            writeScreenshot(png, filePath);
        });
    }, 3000);
});

1 个答案:

答案 0 :(得分:2)

我放弃了使用电子传递的API。我建议使用desktop-screenshot包 - &gt; https://www.npmjs.com/package/desktop-screenshot。这对我来说是跨平台(linux,mac,win)。 windows上的注意我们需要hazardous package,因为当您使用asar打包电子应用时,它无法在内部执行脚本desktop-screenshot。有关危险包装页面的更多信息。

以下是我的代码现在大致有效的方法,请不要复制/粘贴,因为它可能不适合您的解决方案!!但是,它可能会说明如何解决它。

/* ******************************************************************** */
/* MODULE IMPORTS */
import { remote, nativeImage } from 'electron';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
import moment from 'moment';
import screenshot from 'desktop-screenshot';
/* */
/*/********************************************************************///
/* ******************************************************************** */
/* CLASS */
export default class ScreenshotTaker {    
    constructor() {
        this.name = "ScreenshotTaker";        
    }
    start(cb) {
        const fileName = `cap_${moment().format('YYYYMMDD_HHmmss')}.png`;
        const destFolder = global.config.app('capture.screenshots');
        const outputPath = path.join(destFolder, fileName);        
        const platform = os.platform();
        if(platform === 'win32') {
            this.performWindowsCapture(cb, outputPath);
        }
        if(platform === 'darwin') {
            this.performMacOSCapture(cb, outputPath);
        }
        if(platform === 'linux') {
            this.performLinuxCapture(cb, outputPath);
        }
    }
    performLinuxCapture(cb, outputPath) {
        // debian
        exec(`import -window root "${outputPath}"`, (error, stdout, stderr) => {
            if(error) {
                cb(error, null, outputPath);
            } else {
                cb(null, stdout, outputPath);
            }
        });
    }
    performMacOSCapture(cb, outputPath) {
        this.performWindowsCapture(cb, outputPath);
    }
    performWindowsCapture(cb, outputPath) {
        require('hazardous');
        screenshot(outputPath, (err, complete) => {
            if(err) {
                cb(err, null, outputPath);
            } else {
                cb(null, complete, outputPath);
            }
        });
    }
}
/*/********************************************************************///