• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3require('../common');
4const assert = require('assert');
5
6const {
7  Worker, MessageChannel
8} = require('worker_threads');
9
10const channel = new MessageChannel();
11const workerData = { mesage: channel.port1 };
12const transferList = [channel.port1];
13const meowScript = () => 'meow';
14
15{
16  // Should receive the transferList param.
17  new Worker(`${meowScript}`, { eval: true, workerData, transferList });
18}
19
20{
21  // Should work with more than one MessagePort.
22  const channel1 = new MessageChannel();
23  const channel2 = new MessageChannel();
24  const workerData = { message: channel1.port1, message2: channel2.port1 };
25  const transferList = [channel1.port1, channel2.port1];
26  new Worker(`${meowScript}`, { eval: true, workerData, transferList });
27}
28
29{
30  const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
31  assert.strictEqual(uint8Array.length, 4);
32  new Worker(`
33    const { parentPort, workerData } = require('worker_threads');
34    parentPort.postMessage(workerData);
35    `, {
36    eval: true,
37    workerData: uint8Array,
38    transferList: [uint8Array.buffer]
39  }).on(
40    'message',
41    (message) =>
42      assert.deepStrictEqual(message, Uint8Array.of(1, 2, 3, 4))
43  );
44  assert.strictEqual(uint8Array.length, 0);
45}
46
47{
48  // Should throw on non valid transferList input.
49  const channel1 = new MessageChannel();
50  const channel2 = new MessageChannel();
51  const workerData = { message: channel1.port1, message2: channel2.port1 };
52  assert.throws(() => new Worker(`${meowScript}`, {
53    eval: true,
54    workerData,
55    transferList: []
56  }), {
57    code: 'ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST',
58    message: 'Object that needs transfer was found in message but not ' +
59             'listed in transferList'
60  });
61}
62