• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3const assert = require('assert');
4const { spawn } = require('child_process');
5
6// Check that, once a child process has ended, it’s safe to read from a pipe
7// that the child had used as input.
8// We simulate that using cat | (head -n1; ...)
9
10const p1 = spawn('cat', { stdio: ['pipe', 'pipe', 'inherit'] });
11const p2 = spawn('head', ['-n1'], { stdio: [p1.stdout, 'pipe', 'inherit'] });
12
13// First, write the line that gets passed through p2, making 'head' exit.
14p1.stdin.write('hello\n');
15p2.stdout.setEncoding('utf8');
16p2.stdout.on('data', common.mustCall((chunk) => {
17  assert.strictEqual(chunk, 'hello\n');
18}));
19p2.on('exit', common.mustCall(() => {
20  // We can now use cat’s output, because 'head' is no longer reading from it.
21  p1.stdin.end('world\n');
22  p1.stdout.setEncoding('utf8');
23  p1.stdout.on('data', common.mustCall((chunk) => {
24    assert.strictEqual(chunk, 'world\n');
25  }));
26  p1.stdout.resume();
27}));
28