index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**!
  2. * sendmessage - index.js
  3. *
  4. * Copyright(c) fengmk2 and other contributors.
  5. * MIT Licensed
  6. *
  7. * Authors:
  8. * fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
  9. */
  10. 'use strict';
  11. /**
  12. * Module dependencies.
  13. */
  14. var IS_NODE_DEV_RUNNER = /node\-dev$/.test(process.env._ || '');
  15. if (!IS_NODE_DEV_RUNNER && process.env.IS_NODE_DEV_RUNNER) {
  16. IS_NODE_DEV_RUNNER = true;
  17. }
  18. module.exports = function send(child, message) {
  19. if (typeof child.send !== 'function') {
  20. // not a child process
  21. return setImmediate(child.emit.bind(child, 'message', message));
  22. }
  23. if (IS_NODE_DEV_RUNNER || process.env.SENDMESSAGE_ONE_PROCESS) {
  24. // run with node-dev, only one process
  25. // https://github.com/node-modules/sendmessage/issues/1
  26. return setImmediate(child.emit.bind(child, 'message', message));
  27. }
  28. // cluster.fork(): child.process is process
  29. // childprocess.fork(): child is process
  30. var connected = child.process ? child.process.connected : child.connected;
  31. if (connected) {
  32. return child.send(message);
  33. }
  34. // just log warnning message
  35. var pid = child.process ? child.process.pid : child.pid;
  36. var err = new Error('channel closed');
  37. console.warn('[%s][sendmessage] WARN pid#%s channel closed, nothing send\nstack: %s',
  38. Date(), pid, err.stack);
  39. };