Realm.Worker

A Realm Worker can be used to process Sync events in multiple automatically-managed child processes.

Similar to Web Workers, a Worker is initialized by passing it the name of a module which should be loaded in the new process. The module should export a function for each even type it wishes to handle, which will be called when that event is emitted.

Currently supported events:

  • 'available': Emitted whenever there is a new Realm which has a virtual path matching the filter regex, either due to the Realm being newly created or the listener being added. The virtual path (i.e. the portion of the URL after the protocol and hostname) is passed as an argument.
  • 'change': Emitted whenever the data within a Realm matching the filter regex has changed. A ChangeEvent argument is passed containing information about which Realm changed and what objects within the Realm changed.
  • 'delete': Emitted whenever a Realm matching the filter regex has been deleted from the server. The virtual path of the Realm being deleted is passed as an argument.

Worker automatically spawns child processes as needed to handle events in parallel (up to the limit specified in the options parameter). Events for each specific Realm will be processes in serial in the order in which the events occurred, but may not all be processed in the same child.

new Realm.Worker(moduleName, options)

Create a new Worker which executes the given module.

Parameters:
  • moduleName
    • Type: string
    • The module to load in the worker process.

  • options optional
    • Type: object
    • An object containing option properties to configure the worker. Available properties are as follows:

      • maxWorkers: The maximum number of child processes to spawn. Defaults to os.cpus().length.
      • env: An object containing environment variables to set for the child process.
      • execArgv: Command-line arguments to pass to the node worker processes.
Example:
// my-worker.js
function onchange(path) {
   console.log(`Realm created at ${path}`);
}

function onavailable(change) {
   console.log(`Realm at ${change.path} changed`);
}

function ondelete(path) {
   console.log(`Realm at ${path} deleted`);
}

module.exports = {onchange, oncavailable, ondelete};

// server script
Realm.Sync.addListener(realmServerURL, adminUser, '.*', new Realm.Worker('my-worker'));