control-child.ts 786 B

123456789101112131415161718192021
  1. /** A plain Node child that echoes binary control bytes independently of stdio. */
  2. import { pathToFileURL } from 'node:url'
  3. import type { Duplex } from 'node:stream'
  4. const helper = await import(pathToFileURL(process.argv[2] as string).href) as { openInheritedControlChannel(): Duplex }
  5. const channel = helper.openInheritedControlChannel()
  6. const size = Number(process.argv[3])
  7. process.stdout.write('ordinary stdout\n')
  8. process.stderr.write('ordinary stderr\n')
  9. const chunks: Buffer[] = []
  10. let received = 0
  11. channel.on('error', (error) => { throw error })
  12. channel.on('data', (chunk: Buffer) => {
  13. chunks.push(chunk)
  14. received += chunk.length
  15. if (received === size) {
  16. channel.removeAllListeners('data')
  17. channel.write(Buffer.concat(chunks), () => { channel.destroy() })
  18. }
  19. })