stdio.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const aliases = ['stdin', 'stdout', 'stderr'];
  3. const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
  4. const normalizeStdio = options => {
  5. if (!options) {
  6. return;
  7. }
  8. const {stdio} = options;
  9. if (stdio === undefined) {
  10. return aliases.map(alias => options[alias]);
  11. }
  12. if (hasAlias(options)) {
  13. throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
  14. }
  15. if (typeof stdio === 'string') {
  16. return stdio;
  17. }
  18. if (!Array.isArray(stdio)) {
  19. throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
  20. }
  21. const length = Math.max(stdio.length, aliases.length);
  22. return Array.from({length}, (value, index) => stdio[index]);
  23. };
  24. module.exports = normalizeStdio;
  25. // `ipc` is pushed unless it is already present
  26. module.exports.node = options => {
  27. const stdio = normalizeStdio(options);
  28. if (stdio === 'ipc') {
  29. return 'ipc';
  30. }
  31. if (stdio === undefined || typeof stdio === 'string') {
  32. return [stdio, stdio, stdio, 'ipc'];
  33. }
  34. if (stdio.includes('ipc')) {
  35. return stdio;
  36. }
  37. return [...stdio, 'ipc'];
  38. };