Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

109 lines (79 sloc) 1.734 kB

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

Jump to Line
Something went wrong with that request. Please try again.