summaryrefslogtreecommitdiff
path: root/lib/internal/process/worker_thread_only.js
blob: a9332fb4277363150a9c9dfe63361eaac15abd3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';

// This file contains process bootstrappers that can only be
// run in the worker thread.
const {
  getEnvMessagePort,
  threadId
} = internalBinding('worker');

const debug = require('util').debuglog('worker');

const {
  kWaitingStreams,
  ReadableWorkerStdio,
  WritableWorkerStdio
} = require('internal/worker/io');

const {
  createMessageHandler,
  createWorkerFatalExeception
} = require('internal/worker');

const workerStdio = {};

function initializeWorkerStdio() {
  const port = getEnvMessagePort();
  port[kWaitingStreams] = 0;
  workerStdio.stdin = new ReadableWorkerStdio(port, 'stdin');
  workerStdio.stdout = new WritableWorkerStdio(port, 'stdout');
  workerStdio.stderr = new WritableWorkerStdio(port, 'stderr');

  return {
    getStdout() { return workerStdio.stdout; },
    getStderr() { return workerStdio.stderr; },
    getStdin() { return workerStdio.stdin; }
  };
}

function setup() {
  debug(`[${threadId}] is setting up worker child environment`);

  const port = getEnvMessagePort();
  const publicWorker = require('worker_threads');
  port.on('message', createMessageHandler(publicWorker, port, workerStdio));
  port.start();

  return {
    workerFatalExeception: createWorkerFatalExeception(port)
  };
}

module.exports = {
  initializeWorkerStdio,
  setup
};