hyber v0.2.0
hyber
make node.js get power of multi-process.
Experimental
Be cautious if you want to use it in your real projects.
Introduction
As we all know, JavaScript, running in a single main process environment, can deal some specific jobs with another process. Unfortunately we can not create any child process directly.
Thank to the child_process
module provided by Node.js
, we are able to create child processes by shell commands. The most special one, child_process.fork
, can be used to create child processes by JavaScript files.
The trouble is we have to leave the function of the child process an individual file and use the message
mechanism to receive values from the child process. That's not really cool.
Image what if we create a child process as easy as creating a Promise
object, how fantastic it will be.
Principle
The hyber
function will add some details, tranform your function into temporary file and call it.
Suppose you give a function like this
function add(a, b) {
return a + b
}
Then it will be transformed to
`(function add(a, b) {
return a + b
})(arg1, arg2)
`
Once you give the arguments, they will be filled into the string like
;`(function add(a, b) {
return a + b
})(10, 20)
`
Send message to the main process
`const value = (function add(a, b) {
return a + b)
})(10, 20)
process.send(value)
`
Eventually, fork the file and handle the message by Promise.
That's it.
Usage
Import
import hyber from 'hyber'
Install at first
npm install hyber
# or
yarn add hyber
Without Argument
const func = () => 10
const asyncFunc = hyber(func)
// 10
const result = await asyncFunc()
With Arguments
hyber
generates a new function, you should pass the arguments into the new one.
const func = a => a + 10
const asyncFunc = hyber(func)
// 30
const result = await asyncFunc(20)
NOTICE
Since the new function generated by hyber
runs in a completely different process, it can not capture any variables in the current process. You have to pass all variables as arguments.
Use it only if you want to do tons of calculations without blocking the main process.