summaryrefslogtreecommitdiff
path: root/test/parallel/test-readline-async-iterators-destroy.js
blob: ea174d51723aa838b10a34e594d7c13aeadc95e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';

const common = require('../common');
const fs = require('fs');
const { join } = require('path');
const readline = require('readline');
const assert = require('assert');

const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

const filename = join(tmpdir.path, 'test.txt');

const testContents = [
  '',
  '\n',
  'line 1',
  'line 1\nline 2 南越国是前203年至前111年存在于岭南地区的一个国家\nline 3\ntrailing',
  'line 1\nline 2\nline 3 ends with newline\n'
];

async function testSimpleDestroy() {
  for (const fileContent of testContents) {
    fs.writeFileSync(filename, fileContent);

    const readable = fs.createReadStream(filename);
    const rli = readline.createInterface({
      input: readable,
      crlfDelay: Infinity
    });

    const iteratedLines = [];
    for await (const k of rli) {
      iteratedLines.push(k);
      break;
    }

    const expectedLines = fileContent.split('\n');
    if (expectedLines[expectedLines.length - 1] === '') {
      expectedLines.pop();
    }
    expectedLines.splice(1);

    assert.deepStrictEqual(iteratedLines, expectedLines);

    rli.close();
    readable.destroy();
  }
}

async function testMutualDestroy() {
  for (const fileContent of testContents) {
    fs.writeFileSync(filename, fileContent);

    const readable = fs.createReadStream(filename);
    const rli = readline.createInterface({
      input: readable,
      crlfDelay: Infinity
    });

    const expectedLines = fileContent.split('\n');
    if (expectedLines[expectedLines.length - 1] === '') {
      expectedLines.pop();
    }
    expectedLines.splice(2);

    const iteratedLines = [];
    for await (const k of rli) {
      iteratedLines.push(k);
      for await (const l of rli) {
        iteratedLines.push(l);
        break;
      }
      assert.deepStrictEqual(iteratedLines, expectedLines);
    }

    assert.deepStrictEqual(iteratedLines, expectedLines);

    rli.close();
    readable.destroy();
  }
}

testSimpleDestroy().then(testMutualDestroy).then(common.mustCall());