对于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. 04-树5. File Transfer--并查集

    对于一个集合常见的操作有:判断一个元素是否属于一个集合:合并两个集合等等.而并查集是处理一些不相交集合(Disjoint Sets)的合并及查询问题的有利工具. 并查集是利用树结构实现的.一个集合用一 ...

  2. Kruskal-Wallis test

    sklearn实战-乳腺癌细胞数据挖掘(博主亲自录视频) https://study.163.com/course/introduction.htm?courseId=1005269003&u ...

  3. php优秀网摘

    1.thinkphp的目录结构设计经验总结 说明:thinkphp3.2.3对类没有深刻的认识,对项目规模和架构有很糟糕的影响.这里写的目录结构和设计模式相当于对3.2添加了面向对象架构.第二个链接是 ...

  4. html中<meta>标签

    这个是html文档一般都有的元素. 1. 介绍 元素基本所有浏览器都支持,它提供页面的元信息,比如描述.关键字.web服务等 位于文档头部的内部,将以名称/值对出现 2. 属性 注意:如果没有name ...

  5. BZOJ2588:LCA+主席树来实现树上两点之间第K大点权查询

    对于每个节点维护这个节点到根的权值线段树 对于每个询问(x,y),这条路径上的线段树 tree[x]+tree[y]-tree[lca(x,y)]-tree[fa[lca(x,y)]] #includ ...

  6. 调试android chrome web page简明备忘

    必备工具 adb tools.android chrome 先开启手机调试模式 adb forward tcp:9919 localabstract:chrome_devtools_remote 成功 ...

  7. c++刷题(3/100)数独,栈和队列

    stack的基本操作 • s.size():返回栈中的元素数量 • s.empty():判断栈是否为空,返回true或false • s.push(元素):返回对栈顶部“元素”的可变(可修改)引用 • ...

  8. python初步学习-python函数 (二)

    几个特殊的函数(待补充) python是支持多种范型的语言,可以进行所谓函数式编程,其突出体现在有这么几个函数: filter.map.reduce.lambda.yield lambda >& ...

  9. Coursera在线学习---第二节.Octave学习

    1)两个矩阵相乘 A*B 2)两个矩阵元素位相乘(A.B矩阵中对应位置的元素相乘) A.*B 3)矩阵A的元素进行平方 A.^2 4)向量或矩阵中的元素求倒数 1./V    或   1./A 5) ...

  10. pythonif语句和循环语句

    1.if语句用法 # if语句用法(缩进相同的成为一个代码块) score=90 if score>=60: print("合格") print("OK" ...