A complete, functional, fast and simple Node.js threading module.
safe-instances was developed by Oratio.io for Oratio.js's Module System.
It's based on children pools, allowing you to
NOTE: With release 2.0, sending file names when doing new Child() is DEPRECATED. You must do new ChildFile(), as explained in the quick-start tutorial.
npm install safe-instances
var Child = require('safe-instances');
var pool = new Child.Pool(3); //Creates pool with 3 processes
var child = new Child('process.handle("randomMessage", function(value, callback){ callback(value) })', pool, 3 * 60);
child.start();
child.contact('randomMessage', 'myValue') //NOTE: You might pass a third callback argument, too.
.then(function(value){
console.log(value); //<- "myValue"
});Need to send file locations instead of strings when creating new script? Do:
var Child = require('safe-instances');
Child.File.usesCache = false; //Default: true. Caches scripts for being re-used.
var child = new Child.File(__dirname + 'script.js', 3 * 60);
child.start();
[...]Adapter for child.
Boolean. Default: true. If the console.logs running on the child process appear on the parent process, too.
Boolean. Default: false. If require()s are allowed in the child process. Only accept this if the source is trustable.
Function for starting children.
Returns timeout passed on start. Can be changed, but only before Child#start() is called.
Returns code passed as the first argument. Can be changed, but only before Child#start() is called.
Kills child process. A new process is automagically created by the pool.
Return Promise. Contacts child. Example:
// Parent
child.contact('database query', 'SELECT * FROM Table')
.then(function(rows){
console.log(rows); //Yay! Did a query in a child process!
}).catch(function(error){
console.error(error); //Query error.
});
//Child
process.handle('database query', function(argument){
return db.query(argument); //Can even be synchronous, we're on a child process.
});Please note that if there's a fatal contact failure, an error will be actually thrown, so there's no need to handle safe-instances errors in the returned promise.
Shares API with Child. Getting Started guide already covers everything.