|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | +const assert = require('assert'); |
| 4 | +const path = require('path'); |
| 5 | +const fs = require('fs'); |
| 6 | +const spawn = require('child_process').spawn; |
| 7 | +const tmpdir = require('../common/tmpdir'); |
| 8 | + |
| 9 | +let cat, grep, wc; |
| 10 | + |
| 11 | +const KB = 1024; |
| 12 | +const MB = KB * KB; |
| 13 | + |
| 14 | + |
| 15 | +// Make sure process chaining allows desired data flow: |
| 16 | +// check cat <file> | grep 'x' | wc -c === 1MB |
| 17 | +// This helps to make sure no data is lost between pipes. |
| 18 | + |
| 19 | +{ |
| 20 | + tmpdir.refresh(); |
| 21 | + const file = path.resolve(tmpdir.path, 'data.txt'); |
| 22 | + const buf = Buffer.alloc(MB).fill('x'); |
| 23 | + |
| 24 | + // Most OS commands that deal with data, attach special |
| 25 | + // meanings to new line - for example, line buffering. |
| 26 | + // So cut the buffer into lines at some points, forcing |
| 27 | + // data flow to be split in the stream. |
| 28 | + for (let i = 0; i < KB; i++) |
| 29 | + buf[i * KB] = 10; |
| 30 | + fs.writeFileSync(file, buf.toString()); |
| 31 | + |
| 32 | + cat = spawn('cat', [file]); |
| 33 | + grep = spawn('grep', ['x'], { stdio: [cat.stdout, 'pipe', 'pipe'] }); |
| 34 | + wc = spawn('wc', ['-c'], { stdio: [grep.stdout, 'pipe', 'pipe'] }); |
| 35 | + |
| 36 | + wc.stdout.on('data', common.mustCall(function(data) { |
| 37 | + assert.strictEqual(data.toString().trim(), MB.toString()); |
| 38 | + })); |
| 39 | + |
| 40 | + cat.on('exit', common.mustCall(function(code) { |
| 41 | + assert.strictEqual(code, 0); |
| 42 | + })); |
| 43 | + |
| 44 | + grep.on('exit', common.mustCall(function(code) { |
| 45 | + assert.strictEqual(code, 0); |
| 46 | + })); |
| 47 | + |
| 48 | + wc.on('exit', common.mustCall(function(code) { |
| 49 | + assert.strictEqual(code, 0); |
| 50 | + })); |
| 51 | +} |
0 commit comments