messageParent.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = messageParent;
  6. var _types = require('../types');
  7. /**
  8. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  9. *
  10. * This source code is licensed under the MIT license found in the
  11. * LICENSE file in the root directory of this source tree.
  12. */
  13. const isWorkerThread = (() => {
  14. try {
  15. // `Require` here to support Node v10
  16. const {isMainThread, parentPort} = require('worker_threads');
  17. return !isMainThread && parentPort != null;
  18. } catch {
  19. return false;
  20. }
  21. })();
  22. function messageParent(message, parentProcess = process) {
  23. if (isWorkerThread) {
  24. // `Require` here to support Node v10
  25. const {parentPort} = require('worker_threads'); // ! is safe due to `null` check in `isWorkerThread`
  26. parentPort.postMessage([_types.PARENT_MESSAGE_CUSTOM, message]);
  27. } else if (typeof parentProcess.send === 'function') {
  28. parentProcess.send([_types.PARENT_MESSAGE_CUSTOM, message]);
  29. } else {
  30. throw new Error('"messageParent" can only be used inside a worker');
  31. }
  32. }