0.1.1 • Published 12 years ago

dnode-worker v0.1.1

Weekly downloads
13
License
-
Repository
github
Last release
12 years ago

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(a + 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(a * 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

0.1.1

12 years ago

0.1.0

12 years ago

0.0.2

13 years ago

0.0.1

13 years ago