• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common');
4const fs = require('fs');
5const { join } = require('path');
6const readline = require('readline');
7const assert = require('assert');
8
9const tmpdir = require('../common/tmpdir');
10tmpdir.refresh();
11
12const filename = join(tmpdir.path, 'test.txt');
13
14const testContents = [
15  '',
16  '\n',
17  'line 1',
18  'line 1\nline 2 南越国是前203年至前111年存在于岭南地区的一个国家\nline 3\ntrailing',
19  'line 1\nline 2\nline 3 ends with newline\n',
20];
21
22async function testSimple() {
23  for (const fileContent of testContents) {
24    fs.writeFileSync(filename, fileContent);
25
26    const readable = fs.createReadStream(filename);
27    const rli = readline.createInterface({
28      input: readable,
29      crlfDelay: Infinity
30    });
31
32    const iteratedLines = [];
33    for await (const k of rli) {
34      iteratedLines.push(k);
35    }
36
37    const expectedLines = fileContent.split('\n');
38    if (expectedLines[expectedLines.length - 1] === '') {
39      expectedLines.pop();
40    }
41    assert.deepStrictEqual(iteratedLines, expectedLines);
42    assert.strictEqual(iteratedLines.join(''), fileContent.replace(/\n/g, ''));
43  }
44}
45
46async function testMutual() {
47  for (const fileContent of testContents) {
48    fs.writeFileSync(filename, fileContent);
49
50    const readable = fs.createReadStream(filename);
51    const rli = readline.createInterface({
52      input: readable,
53      crlfDelay: Infinity
54    });
55
56    const expectedLines = fileContent.split('\n');
57    if (expectedLines[expectedLines.length - 1] === '') {
58      expectedLines.pop();
59    }
60    const iteratedLines = [];
61    let iterated = false;
62    for await (const k of rli) {
63      // This outer loop should only iterate once.
64      assert.strictEqual(iterated, false);
65      iterated = true;
66
67      iteratedLines.push(k);
68      for await (const l of rli) {
69        iteratedLines.push(l);
70      }
71      assert.deepStrictEqual(iteratedLines, expectedLines);
72    }
73    assert.deepStrictEqual(iteratedLines, expectedLines);
74  }
75}
76
77testSimple().then(testMutual).then(common.mustCall());
78