-
Notifications
You must be signed in to change notification settings - Fork 1
/
iyem.js
84 lines (79 loc) · 1.97 KB
/
iyem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const fs = require('fs')
const path = require('path')
const fork = require('child_process').fork
const OUTPUT = __dirname+"/tmp/"
function placeNewFnHead(fnStr){
body = fnStr.substr(fnStr.indexOf("{"))
return "function job(param)"+body
}
function generateScript(fn,tag){
tpl = fs.readFileSync(__dirname+"/tplScript.js", "utf-8")
fnStr = placeNewFnHead(fn.toString())
tag = "$.tag='"+tag+"';"
return tpl.replace("//here",tag+fnStr)
}
function Paijem(id,param){
this.child = false
this.isRunning = false
this.on = function(topic,fn){
let self = this
this.child.on('message', message => {
obj = JSON.parse(message)
if(topic == obj.topic) {
if(obj.error) {
fn && fn(null,obj.data)
}else{
fn && fn(obj.data)
}
}
})
}
this.onFinish = function(fn){
this.on("finish",function(data,err){
fn && fn(data,err)
fs.unlinkSync(OUTPUT+id+".js")
})
}
this.onAborted = function(fn){
this.on("aborted",fn)
}
this.start = function(){
this.child = fork(path.resolve(OUTPUT+id+".js"),[JSON.stringify(param)])
this.isRunning = true
return this
}
this.onError = function(fn){
this.on("error",fn)
}
this.pub = function(topic,data){
if(!this.isRunning) return false
let obj = {}
obj.topic = topic
obj.data = data
this.child.send(JSON.stringify(obj))
}
this.sub = function(topic,fn){
this.on(topic,fn)
}
this.stop = function(){
if(!this.isRunning) return false
this.child.kill('SIGINT')
}
this.then = function(othersPaijem){
this.onFinish(othersPaijem.start)
return this
}
}
function Iyem(options){
this.process = false
this.create = function (fn,param,tag){
let id = (new Date()).getTime()
if(typeof param == "undefined") param = {}
if(typeof tag == "undefined") tag = id
if(typeof fn == "function") {
fs.writeFileSync(OUTPUT+id+".js", generateScript(fn,tag), "utf-8");
return new Paijem(id,param)
}
}
}
module.exports = new Iyem()