dnode-worker

0.1.1 • Public • Published

dnode-worker

Stupid simple workers for DNode

Installation

npm install dnode-worker

In three flavors!

Passing a function:

Worker(function (remote, conn) {
  var crypto = require('crypto');
  this.hash = function (s, callback) {
    callback(crypto.createHash('sha1').update(s).digest('hex'));
  }
}, function (worker) {
  worker.hash('foo', function (result) {
    // Do something with the result
 
    // Exit worker
    worker.exit();
  });
});
 

Passing an object:

var Worker = require('dnode-worker');
 
Worker({
  add: function (a, b, callback) {
    callback(+ b);
  }
}, function (worker, exit) {
  worker.add(1, 2, function (result) {
    console.log(result); // 3
 
    // Exit worker
    exit(); // or worker.exit()
  });
});
 

Using a module file:

simple-worker.js

exports.multiply = function (a, b, callback) {
  callback(* b)
}
 
exports.aSlowTask = function (callback) {
  var array = []
  for (var i = 0; i < 70000; i++) {
    array = array.concat([i])
  }
  callback()
}
 

app.js

var Worker = require('dnode-worker');
 
Worker.createWorker(__dirname + '/simple-worker', function (worker, exit) {
  worker.multiply(5, 5, function (result) {
    console.log(result); // 25
  });
  worker.aSlowTask(function () {
    // Exit worker
    exit(); // or worker.exit()
  });
});
 

Error handling:

Worker.createWorker({
  throwTask: function () {
    throw new Error('Some error');
  }
}, function (worker, exit) {
  worker.throwTask();
}).on('error', function (err) { // Attach error listener
  // Handle error
  console.error(err.stack)
 
  // Exit worker
  this.exit();
});
 

Licence

MIT/X11

Readme

Keywords

none

Package Sidebar

Install

npm i dnode-worker

Weekly Downloads

0

Version

0.1.1

License

none

Last publish

Collaborators

  • stagas