对于electron以及nodejs开发,是一只小菜鸟,第一次想做个应用

只能边学边做,遇到各种各样的问题。

1、不想把所有的主进程函数放到一个文件中,这样文件比较乱,并且不好处理

想法:将另一个js文件引入到该文件中,进行调用等

问题:js不存在互相调用的功能

解决方案:

自定义nodejs模块,并在main.js中导入,然后进行处理(以下代码来自网络)

 'use strict';
const electron = require('electron');
const app = electron.app;
const CrawlService = require('./libs/crawlService'); //start crawl service
CrawlService.start(); // adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')(); // prevent window being garbage collected
let mainWindow; function onClosed() {
// dereference the window
// for multiple windows store them in an array
mainWindow = null;
} function createMainWindow() {
const win = new electron.BrowserWindow({
width: 1200,
height: 800
}); win.loadURL(`file://${__dirname}/static/index.html`);
win.openDevTools();
win.on('closed', onClosed); return win;
} app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
}); app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow();
}
}); app.on('ready', () => {
mainWindow = createMainWindow();
})

以上代码中的4、5、6、7行就是引入自定义模块进行处理,自定义模块代码为

const request = require('request'),
async = require('async'),
ipcMain = require('electron').ipcMain,
db = require('./dbService'),
cheerio = require('cheerio'); const CrawlService = {
start: function () {
ipcMain.on('search-keyword', function (event, keyword) {
console.log('channel "search-keyword" on msg:' + keyword); let match = {$regex: eval('/' + keyword + '/')};
var query = keyword ? {$or: [{title: match}, {content: match}]} : {};
db.find(query).sort({publishDate: -1}).limit(100).exec(function (err, mails) {
event.sender.send('search-reply', {mails: mails});
});
}); ipcMain.on('start-crawl', (event, arg) => {
console.log('channel "start-crawl" on msg:' + arg);
var updater = {
sender: event.sender,
channel: arg,
updateProgress: function (progress) {
this.sender.send(this.channel, {progress: progress});
}
};
crawler(updater);
});
}
}; function UrlCrawler(targetUrl) {
return {
targetUrl: targetUrl,
startCrawl: function (processDom) {
request(this.targetUrl, (err, response, body) => {
if (err) throw err;
var $ = cheerio.load(body);
processDom($)
});
}
};
} function pageCrawl(page, totalPage, updater, crawlNextPage, crawProgress) {
new UrlCrawler('http://12345.chengdu.gov.cn/moreMail?page=' + page).startCrawl(($) => {
var $pageMails = $('div.left5 ul li.f12px'),
sameMailsInPage = 0; async.eachOfLimit($pageMails, 10, function iteratee(item, key, nextMail) {
if(crawProgress.skip){
return nextMail();
}
let $item = $(item),
mailDetailUrl = $item.find('a').prop('href'),
divs = $item.find('div');
var mail = {
_id: mailDetailUrl.match(/\d+/g)[0],
title: $(divs[0]).text().trim(),
sender: $(divs[1]).text().trim(),
receiveUnit: $(divs[2]).text().trim(),
status: $(divs[3]).text().trim(),
category: $(divs[4]).text().trim(),
views: $(divs[5]).text().trim()
}; new UrlCrawler('http://12345.chengdu.gov.cn/' + mailDetailUrl).startCrawl(($) => {// crawl mail detail
mail.content = $($('.rightside1 td.td2')[1]).text().trim();
mail.result = $('.rightside1 tbody tr:last-child').text().trim();
mail.publishDate = $($('.rightside1 td.td32')[0]).text().trim() || $($('.rightside1 td.td32')[1]).text().trim(); console.log(mail._id); db.update({_id: mail._id}, mail, {upsert: true, returnUpdatedDocs: true}, function (err, numReplaced, affectedDocuments, upsert) {
if (err) {
throw err;
}
if(!upsert && affectedDocuments.result == mail.result){//if a mail are not update
if(++sameMailsInPage == 15){ //if all mails in one page are note update.
crawProgress.skip = true;
}
}
}); nextMail();
});
}, function done() {
crawlNextPage();
updater.updateProgress(Math.floor(page * 100 / totalPage));
});
});
} /**
* 1. get total page size
* 2. iterator from page 1 to totalSize
* 2.1 fetch mails summary list on 1 page
* 2.2 iterator from mails 1 to maxItems mails summary in 1 page
* 2.2.1 fetch mails detail from url
* 2.2.2 save mail to db
* 2.3 test if none of mails in current page updated? if none, stop crawling or continue step 2.
*
* @param url
*/
function crawler(updater) {
new UrlCrawler('http://12345.chengdu.gov.cn/moreMail').startCrawl(($) => {
var totalSize = $('div.pages script').html().match(/iRecCount = \d+/g)[0].match(/\d+/g)[0],
totalPageSize = Math.ceil(totalSize / 15),
pagesCollection = [],
crawProgress = {skip: false};
for (let i = 1; i <= totalPageSize; i++) {
pagesCollection.push(i);
}
async.eachSeries(pagesCollection, function (page, crawlNextPage) {
pageCrawl(page, totalPageSize, updater, crawlNextPage, crawProgress);
})
});
} module.exports = CrawlService;

electron主进程引入自定义模块的更多相关文章

  1. Visual Studio Code调试electron主进程

    Visual Studio Code调试electron主进程 作者: jekkay 分类: electron 发布时间: 2017-06-11 14:56  一·概述 此文原出自[水滴石]: htt ...

  2. 研究Electron主进程、渲染进程、webview之间的通讯

    背景 由于某个Electron应用,需要主进程.渲染进程.webview之间能够互相通讯. 不过因为Electron仅提供了主进程与渲染进程的通讯,没有渲染进程之间或渲染进程与webview之间通讯的 ...

  3. electron 主进程,和渲染进程的通信

    ipcMain https://electronjs.org/docs/api/ipc-main 当在主进程中使用时,它处理从渲染器进程(网页)发送出来的异步和同步信息, 当然也有可能从主进程向渲染进 ...

  4. python引入自定义模块

    Python的包搜索路径 Python会在以下路径中搜索它想要寻找的模块:1. 程序所在的文件夹2. 标准库的安装路径3. 操作系统环境变量PYTHONPATH所包含的路径 将自定义库的路径添加到Py ...

  5. Python 如何引入自定义模块

    Python 中如何引用自己创建的源文件(*.py)呢? 也就是所谓的模块. 假如,你有一个自定义的源文件,文件名:saySomething.py .里面有个函数,函数名:sayHello.如下图: ...

  6. 使用Visual Studio Code调试Electron主进程

    1.打开VS Code,使用文件->打开,打开程序目录 2.切换到调试选项卡 3.打开launch.json配置文件 4.在“附加到进程”节点上增加localhost配置 5.使用命令行启动el ...

  7. [转]Python如何引入自定义模块?

    转自 http://www.cnblogs.com/JoshuaMK/p/5205398.html Python运行环境在查找库文件时是对 sys.path 列表进行遍历,如果我们想在运行环境中注册新 ...

  8. Python如何引入自定义模块?

    Python运行环境在查找库文件时是对 sys.path 列表进行遍历,如果我们想在运行环境中注册新的类库,主要有以下四种方法: 1.在sys.path列表中添加新的路径.这里可以在运行环境中直接修改 ...

  9. 自己实现一个Electron跨进程消息组件

    我们知道开发Electron应用,难免要涉及到跨进程通信,以前Electron内置了remote模块,极大的简化了跨进程通信的开发工作,但这也带来了很多问题,具体的细节请参与我之前写的文章: http ...

随机推荐

  1. syntax error: non-declaration statement outside function body

    在函数外部使用形如:name:="mark"这样语句会出现 syntax error: non-declaration statement outside function bod ...

  2. (二)SMO算法

    11 SMO优化算法(Sequential minimal optimization) SMO算法由Microsoft Research的John C. Platt在1998年提出,并成为最快的二次规 ...

  3. css等比例分割父级容器(完美三等分)

    html部分代码: 方法一: 浮动布局+百分比 (将子元素依次左浮动,根据子元素的个数,设定每个子元素的宽度百分比) 方法二:行内元素(inline-block)+百分比 方法三: 父元素  disp ...

  4. Xshell连接Linux服务器总掉线

    Xshell连接linux服务器总掉线,解决办法如下: 1.登录服务器后 [root@test134 ~]# cd /etc/ssh/ [root@test134 ssh]# vim sshd_con ...

  5. net 加密-解密

    #region DES加密 解密 //key:32位 public string DESEncrypt(string strSource, byte[] key) { System.Security. ...

  6. javascript中字符串的两种定义形式

    1.var s = "this is a string";  var t = "this is also a string"; s.test = 20; 2.v ...

  7. windows+python3.6下安装fasttext+fasttext在win上的使用+gensim(fasttext)

    真是坑了好久,faxttext对win并不是很友好,所以遇到了很多坑,记录下来,以供大家少走弯路. 法1:刚开始直接用pip install fasttext,最后一直报下面这个错误 “error:M ...

  8. Tinyos Makerules解读

    Makerules 文件解读 位于/opt/tinyos-2.1.2/support/make #-*-Makefile-*- vim:syntax=make #$Id: Makerules,v 1. ...

  9. Function.prototype.bind 简介

    bind可以解决两种问题: 1. 可以改变一个函数的 this 指向 2. 可以实现偏函数等高阶功能 本文暂且讨论第一个功能 USE CASE var foo = { x: 3 } var bar = ...

  10. Coursera在线学习---第五节.Logistic Regression

    一.假设函数与决策边界 二.求解代价函数 这样推导后最后发现,逻辑回归参数更新公式跟线性回归参数更新方式一摸一样. 为什么线性回归采用最小二乘法作为求解代价函数,而逻辑回归却用极大似然估计求解? 解答 ...