handle-async.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import {createReadStream, createWriteStream} from 'node:fs';
  2. import {Buffer} from 'node:buffer';
  3. import {Readable, Writable, Duplex} from 'node:stream';
  4. import {generatorToStream} from '../transform/generator.js';
  5. import {handleStdio} from './handle.js';
  6. import {TYPE_TO_MESSAGE} from './type.js';
  7. // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode
  8. export const handleStdioAsync = (options, verboseInfo) => handleStdio(addPropertiesAsync, options, verboseInfo, false);
  9. const forbiddenIfAsync = ({type, optionName}) => {
  10. throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);
  11. };
  12. // Create streams used internally for piping when using specific values for the `std*` options, in async mode.
  13. // For example, `stdout: {file}` creates a file stream, which is piped from/to.
  14. const addProperties = {
  15. fileNumber: forbiddenIfAsync,
  16. generator: generatorToStream,
  17. asyncGenerator: generatorToStream,
  18. nodeStream: ({value}) => ({stream: value}),
  19. webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {
  20. const objectMode = writableObjectMode || readableObjectMode;
  21. const stream = Duplex.fromWeb(transform, {objectMode});
  22. return {stream};
  23. },
  24. duplex: ({value: {transform}}) => ({stream: transform}),
  25. native() {},
  26. };
  27. const addPropertiesAsync = {
  28. input: {
  29. ...addProperties,
  30. fileUrl: ({value}) => ({stream: createReadStream(value)}),
  31. filePath: ({value: {file}}) => ({stream: createReadStream(file)}),
  32. webStream: ({value}) => ({stream: Readable.fromWeb(value)}),
  33. iterable: ({value}) => ({stream: Readable.from(value)}),
  34. asyncIterable: ({value}) => ({stream: Readable.from(value)}),
  35. string: ({value}) => ({stream: Readable.from(value)}),
  36. uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),
  37. },
  38. output: {
  39. ...addProperties,
  40. fileUrl: ({value}) => ({stream: createWriteStream(value)}),
  41. filePath: ({value: {file, append}}) => ({stream: createWriteStream(file, append ? {flags: 'a'} : {})}),
  42. webStream: ({value}) => ({stream: Writable.fromWeb(value)}),
  43. iterable: forbiddenIfAsync,
  44. asyncIterable: forbiddenIfAsync,
  45. string: forbiddenIfAsync,
  46. uint8Array: forbiddenIfAsync,
  47. },
  48. };