Tutorial: 3-CallableTask

3-CallableTask

The Callable Task takes a script path as does the ScriptTask. It allows the worker to call function, and expect (or not) ans answer.

Using an archiver task that will zip a directory:

The Task:

//task.js
var archiver = require('archiver')
var fs = require('fs')
var channel = process.relieve.ipc
var archive

function archiveDirectory(dir) {
  archive = archiver('zip')
  var output = fs.createWriteStream('archive.zip')

  output.on('close', function() {
    channel.send('finish', archive.pointer() + ' bytes written')
  })

  archive.on('error', function(err) { throw err })

  archive.pipe(output)

  archive.directory('./', 'dest')
  archive.finalize()
}

module.exports = {
  archiveDirectory: archiveDirectory,
  bytesWritten: function() { return archive.pointer() }
}

The Callable Task can call the archiveDirectory method. It'll launch an archive and it then calls bytesWritten to get back some progression. When the task finishes, we clear the interval and print the final message.

The Worker:

//worker.js
var CallableTask = require('relieve/tasks/CallableTask')

var task = new CallableTask('task.js', {restart: true})

task.start()
.then(function() {
  task.call('archiveDirectory', './directory')

  var bytesInterval = setInterval(function() {
    console.log(task.get('bytesWritten'))
  }, 100)

  task.once('finish', function(message) {
    console.log(message)
    clearInterval(bytesInterval)
  })
})