1'use strict'; 2 3const common = require('../common'); 4const fs = require('fs'); 5const { once } = require('events'); 6const { join } = require('path'); 7const readline = require('readline'); 8const assert = require('assert'); 9 10const tmpdir = require('../common/tmpdir'); 11tmpdir.refresh(); 12 13const filename = join(tmpdir.path, 'test.txt'); 14 15const testContents = [ 16 '', 17 '\n', 18 'line 1', 19 'line 1\nline 2 南越国是前203年至前111年存在于岭南地区的一个国家\nline 3\ntrailing', 20 'line 1\nline 2\nline 3 ends with newline\n', 21]; 22 23async function testSimpleDestroy() { 24 for (const fileContent of testContents) { 25 fs.writeFileSync(filename, fileContent); 26 27 const readable = fs.createReadStream(filename); 28 const rli = readline.createInterface({ 29 input: readable, 30 crlfDelay: Infinity 31 }); 32 33 const iteratedLines = []; 34 for await (const k of rli) { 35 iteratedLines.push(k); 36 break; 37 } 38 39 const expectedLines = fileContent.split('\n'); 40 if (expectedLines[expectedLines.length - 1] === '') { 41 expectedLines.pop(); 42 } 43 expectedLines.splice(1); 44 45 assert.deepStrictEqual(iteratedLines, expectedLines); 46 47 rli.close(); 48 readable.destroy(); 49 50 await once(readable, 'close'); 51 } 52} 53 54async function testMutualDestroy() { 55 for (const fileContent of testContents) { 56 fs.writeFileSync(filename, fileContent); 57 58 const readable = fs.createReadStream(filename); 59 const rli = readline.createInterface({ 60 input: readable, 61 crlfDelay: Infinity 62 }); 63 64 const expectedLines = fileContent.split('\n'); 65 if (expectedLines[expectedLines.length - 1] === '') { 66 expectedLines.pop(); 67 } 68 expectedLines.splice(2); 69 70 const iteratedLines = []; 71 for await (const k of rli) { 72 iteratedLines.push(k); 73 for await (const l of rli) { 74 iteratedLines.push(l); 75 break; 76 } 77 assert.deepStrictEqual(iteratedLines, expectedLines); 78 } 79 80 assert.deepStrictEqual(iteratedLines, expectedLines); 81 82 rli.close(); 83 readable.destroy(); 84 85 await once(readable, 'close'); 86 } 87} 88 89testSimpleDestroy().then(testMutualDestroy).then(common.mustCall()); 90