From 56ceb5efd24d3e50282d741d39f3d5afacf29202 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sun, 10 Sep 2017 05:07:13 +0200 Subject: [PATCH] doc: add documentation for workers module --- doc/api/_toc.md | 1 + doc/api/domain.md | 3 + doc/api/process.md | 80 ++++++++++++ doc/api/vm.md | 21 +++ doc/api/worker.md | 274 +++++++++++++++++++++++++++++++++++++++ tools/doc/type-parser.js | 2 + 6 files changed, 381 insertions(+) create mode 100644 doc/api/worker.md diff --git a/doc/api/_toc.md b/doc/api/_toc.md index b3987ed8e4..36f528132b 100644 --- a/doc/api/_toc.md +++ b/doc/api/_toc.md @@ -50,6 +50,7 @@ * [Utilities](util.html) * [V8](v8.html) * [VM](vm.html) +* [Worker](worker.html) * [ZLIB](zlib.html)
diff --git a/doc/api/domain.md b/doc/api/domain.md index a4a31d4fec..64c81e0244 100644 --- a/doc/api/domain.md +++ b/doc/api/domain.md @@ -25,6 +25,8 @@ will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to exit immediately with an error code. +*Note*: This module is not available in [`Worker`][]s. + ## Warning: Don't Ignore Errors! @@ -505,3 +507,4 @@ rejections. [`setInterval()`]: timers.html#timers_setinterval_callback_delay_args [`setTimeout()`]: timers.html#timers_settimeout_callback_delay_args [`throw`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw +[`Worker`]: #worker_class_worker diff --git a/doc/api/process.md b/doc/api/process.md index 7ff5b8e712..138e86769c 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -338,6 +338,15 @@ The `*-deprecation` command line flags only affect warnings that use the name See the [`process.emitWarning()`][process_emit_warning] method for issuing custom or application-specific warnings. +### Event: 'workerMessage' + + +If this thread was spawned by a `Worker`, this event emits messages sent using +[`worker.postMessage()`][]. See the [`port.on('message')`][] event for +more details. + ### Signal Events @@ -412,6 +421,8 @@ added: v0.7.0 The `process.abort()` method causes the Node.js process to exit immediately and generate a core file. +*Note*: This feature is not available in [`Worker`][] threads. + ## process.arch + +* {boolean} + +Returns `true` if this code is not running inside of a [`Worker`][] thread. + ## process.mainModule + +This method is available if this is a `Worker` thread, which can be tested +using [`process.isMainThread`][]. + +Send a message to the parent thread’s `Worker` instance that will be received +via [`worker.on('message')`][]. See [`port.postMessage()`][] for +more details. + ## process.release + +* {integer} + +An integer identifier for the current thread. On the corresponding worker object +(if there is any), it is available as [`worker.threadId`][]. + ## process.title + +An arbitrary JavaScript object that contains a clone of the data passed +to this thread’s `Worker` constructor. + [`'exit'`]: #process_event_exit [`'finish'`]: stream.html#stream_event_finish [`'message'`]: child_process.html#child_process_event_message @@ -1884,6 +1958,8 @@ cases: [`net.Server`]: net.html#net_class_net_server [`net.Socket`]: net.html#net_class_net_socket [`os.constants.dlopen`]: os.html#os_dlopen_constants +[`port.postMessage()`]: worker.html#worker_port_postmessage_value_transferlist +[`port.on('message')`]: worker.html#worker_event_message [`process.argv`]: #process_process_argv [`process.execPath`]: #process_process_execpath [`process.exit()`]: #process_process_exit_code @@ -1894,6 +1970,10 @@ cases: [`require.main`]: modules.html#modules_accessing_the_main_module [`require.resolve()`]: globals.html#globals_require_resolve [`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_args +[`Worker`]: worker.html#worker_worker +[`worker.threadId`]: worker.html#worker_worker_threadid +[`worker.postMessage()`]: worker.html#worker_worker_postmessage_value_transferlist +[`worker.on('message')`]: worker.html#worker_event_message_1 [Child Process]: child_process.html [Cluster]: cluster.html [Duplex]: stream.html#stream_duplex_and_transform_streams diff --git a/doc/api/vm.md b/doc/api/vm.md index dff10b17cf..e43d4c0f9b 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -310,6 +310,27 @@ console.log(util.inspect(sandbox)); // { globalVar: 1024 } ``` +## vm.moveMessagePortToContext(port, context) + + +* `port` {MessagePort} +* `contextifiedSandbox` {Object} A contextified object as returned by the + `vm.createContext()` method. +* Returns: {MessagePort} + +Bind a `MessagePort` to a specific VM context. This returns a new `MessagePort` +object, whose prototype and methods act as if they were created in the passed +context. The received messages will also be emitted as objects from the passed +context. + +Note that the return instance is *not* an `EventEmitter`; for receiving +messages, the `.onmessage` property can be used. + +The `port` object on which this method was called can not be used for sending +or receiving further messages. + ## vm.runInDebugContext(code) + +The `MessageChannel` has no methods of its own. `new MessageChannel()` +yields an object with `port1` and `port2` properties, which refer to linked +[`MessagePort`][] instances. + +```js +const { MessageChannel } = require('worker'); + +const { port1, port2 } = new MessageChannel(); +port1.on('message', (message) => console.log('received', message)); +port2.postMessage({ foo: 'bar' }); +// prints: received { foo: 'bar' } +``` + +## Class: MessagePort + + +* Extends: {EventEmitter} + +Instances of the `worker.MessagePort` class represent an asynchronous +communications channel. It can be used to transfer structured data, +memory regions and other `MessagePort`s between different [`Worker`][]s +or [`vm` context][vm]s. + +For transferring `MessagePort` instances between VM contexts, see +[`vm.moveMessagePortToContext()`][]. + +*Note*: With the exception of `MessagePort`s being [`EventEmitter`][]s rather +than `EventTarget`s, this implementation matches [browser `MessagePort`][]s. + +### Event: 'close' + + +The `'close'` event is emitted once either side of the channel has been +disconnected. + +### Event: 'error' + + +The `'error'` event is emitted if the worker thread throws an uncaught +expection. In that case, the worker will be terminated. + +### Event: 'message' + + +The `'message'` event is emitted for any incoming message, containing the cloned +input of [`port.postMessage()`][]. + +### port.close() + + +* Returns: {undefined} + +Disables further sending of messages on either side of the connection. + +### port.postMessage(value[, transferList]) + + +* Returns: {undefined} + +Sends a JavaScript value to the receiving side of this channel. +`value` will be transferred in a way +that is compatible with the [HTML structured clone algorithm][]. In particular, +it may contain circular references and objects like typed arrays that `JSON` +is not able to serialize. + +`transferList` may be a list of `ArrayBuffer` and `MessagePort` objects. +After transferring, they will not be usable on the sending side of the channel +anymore. + +If `value` contains [`SharedArrayBuffer`][] instances, those will be accessible +from either thread. + +### port.start() + + +* Returns: {undefined} + +Starts receiving messages on this `MessagePort`. When using this port +as an event emitter, this will be called automatically once `message` listeners +are attached. + +## Class: Worker + + +The `Worker` class represents an independent JavaScript execution thread. +Most Node APIs are available inside of it. + +Notable differences inside a Worker environment are: + +- The [`process.stdin`][], [`process.stdout`][] and [`process.stderr`][] + properties are set to `null`. +- The [`domain`][] module is not usable inside of workers. +- The [`process.isMainThread`][] property is set to `false`. +- The [`process.postMessage()`][] method is available and the + [process.on('`workerMessage`')][] is being emitted on the `process` object. +- [`process.exit()`][] does not stop the whole program, just the single thread, + and [`process.abort()`][] is not available. +- [`process.chdir()`][] as well as `process` methods that set group or user ids + are not available. +- [`process.env`][] is a read-only reference to the environment variables. +- [`process.title`][] can not be modified. +- Native addons that were not build with explicit `Worker` support can not be + loaded. +- Execution may stop at any point as a result of the [`worker.terminate()`][] + method being invoked. +- IPC channels from parent processes are not accessible. + +Creating `Worker` instances inside of other `Worker`s is permitted. + +### new Worker(filename, options) + +* filename {string} The absolute path to the Worker’s main script. + If `options.eval` is true, this is a string containing JavaScript code rather + than a path. +* options {Object} + * eval {boolean} If true, interpret the first argument to the constructor + as a script that is executed once the worker is online. + * data {value} An arbitrary JavaScript value that will be cloned and made + available as [`process.workerData`][]. The cloning will occur as described + in the [HTML structured clone algorithm][], and an error will be thrown + if the object can not be cloned (e.g. because it contains `function`s). + * maxSemiSpaceSize {integer} An optional memory limit in MB for the thread’s + heap’s semi-space, which contains most short-lived objects. + * maxOldSpaceSize {integer} An optional memory limit in MB for the thread’s + main heap. + +### Event: 'exit' + + +* `exitCode` {integer} + +The `'exit'` event is emitted once the worker has stopped. If the worker +exited by calling [`process.exit()`][], the `exitCode` parameter will be the +passed exit code. If the worker was terminated, the `exitCode` parameter will +be `1`. + +### Event: 'message' + + +The `'message'` event is emitted when the worker thread has invoked +[`process.postMessage()`][]. See the [`port.on('message')`][] event for +more details. + +### Event: 'online' + + +The `'online'` event is emitted when the worker thread has started executing +JavaScript code. + +### worker.postMessage(value[, transferList]) + + +Send a message to the worker that will be received via +[`process.on('workerMessage')`][]. See [`port.postMessage()`][] for +more details. + +### worker.terminate([callback]) + + +Stop all JavaScript execution in the worker thread as soon as possible. +`callback` is an optional function that is invoked once this operation is known +to have completed. + +### worker.threadId + + +* {integer} + +An integer identifier for the referenced thread. Inside the worker thread, +it is available as [`process.threadId`][]. + +[`EventEmitter`]: events.html +[`MessagePort`]: #worker_class_messageport +[`port.postMessage()`]: #worker_port_postmessage_value_transferlist +[`Worker`]: #worker_class_worker +[`worker.terminate()`]: #worker_worker_terminate_callback +[`process.isMainThread`]: process.html#process_process_is_main_thread +[`process.exit()`]: process.html#process_process_exit +[`process.abort()`]: process.html#process_process_abort +[`process.chdir()`]: process.html#process_process_chdir_directory +[`process.env`]: process.html#process_process_env +[`process.postMessage()`]: process.html#process_process_post_message_value_transferlist +[`process.stdin`]: process.html#process_process_stdin +[`process.stderr`]: process.html#process_process_stderr +[`process.stdout`]: process.html#process_process_stdout +[`process.threadId`]: process.html#process_process_threadid +[`process.title`]: process.html#process_process_title +[`process.workerData`]: process.html#process_process_workerdata +[`process.on('workerMessage')`]: process.html#process_event_workermessage +[`domain`]: domain.html +[`vm.moveMessagePortToContext()`]: vm.html#vm_vm_movemessageporttocontext_port_context +[vm]: vm.html#vm_vm_executing_javascript +[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +[browser `MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort +[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm diff --git a/tools/doc/type-parser.js b/tools/doc/type-parser.js index 4c2d29f2bf..0cff112f38 100644 --- a/tools/doc/type-parser.js +++ b/tools/doc/type-parser.js @@ -46,6 +46,8 @@ const typeMap = { 'Handle': 'net.html#net_server_listen_handle_backlog_callback', 'net.Socket': 'net.html#net_class_net_socket', + 'MessagePort': 'worker.html#worker_class_messageport', + 'Stream': 'stream.html#stream_stream', 'stream.Readable': 'stream.html#stream_class_stream_readable', 'stream.Writable': 'stream.html#stream_class_stream_writable',