|
1 | 1 |
|
2 |
| -`readline` 的一个常见用例是每次一行地从文件系统[可读流][Readable]消费输入: |
| 2 | +`readline` 的一个常见用例是每次一行地输入文件。 |
| 3 | +最简单的方法是利用 [`fs.ReadStream`] API 以及 `for await...of` 循环: |
3 | 4 |
|
4 | 5 | ```js
|
| 6 | +const fs = require('fs'); |
5 | 7 | const readline = require('readline');
|
| 8 | + |
| 9 | +async function processLineByLine() { |
| 10 | + const fileStream = fs.createReadStream('input.txt'); |
| 11 | + |
| 12 | + const rl = readline.createInterface({ |
| 13 | + input: fileStream, |
| 14 | + crlfDelay: Infinity |
| 15 | + }); |
| 16 | + // 注意:我们使用 crlfDelay 选项将 input.txt 中的所有 CR LF 实例('\r\n')识别为单个换行符。 |
| 17 | + |
| 18 | + for await (const line of rl) { |
| 19 | + // input.txt 中的每一行在这里将会被连续地用作 `line`。 |
| 20 | + console.log(`Line from file: ${line}`); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +processLineByLine(); |
| 25 | +``` |
| 26 | + |
| 27 | +或者,可以使用 [`'line'`] 事件: |
| 28 | + |
| 29 | +```js |
6 | 30 | const fs = require('fs');
|
| 31 | +const readline = require('readline'); |
7 | 32 |
|
8 | 33 | const rl = readline.createInterface({
|
9 | 34 | input: fs.createReadStream('sample.txt'),
|
10 | 35 | crlfDelay: Infinity
|
11 | 36 | });
|
12 | 37 |
|
13 | 38 | rl.on('line', (line) => {
|
14 |
| - console.log(`文件的每行内容:${line}`); |
| 39 | + console.log(`文件中的每一行: ${line}`); |
15 | 40 | });
|
16 | 41 | ```
|
17 | 42 |
|
| 43 | +目前,`for await...of` 循环可能会慢一点。 |
| 44 | +如果 `async` / `await` 流和速度都是必不可少的,可以应用混合方法: |
| 45 | + |
| 46 | +```js |
| 47 | +const { once } = require('events'); |
| 48 | +const { createReadStream } = require('fs'); |
| 49 | +const { createInterface } = require('readline'); |
| 50 | + |
| 51 | +(async function processLineByLine() { |
| 52 | + try { |
| 53 | + const rl = createInterface({ |
| 54 | + input: createReadStream('big-file.txt'), |
| 55 | + crlfDelay: Infinity |
| 56 | + }); |
| 57 | + |
| 58 | + rl.on('line', (line) => { |
| 59 | + // 处理行。 |
| 60 | + }); |
| 61 | + |
| 62 | + await once(rl, 'close'); |
| 63 | + |
| 64 | + console.log('文件已处理'); |
| 65 | + } catch (err) { |
| 66 | + console.error(err); |
| 67 | + } |
| 68 | +})(); |
| 69 | +``` |
| 70 | + |
0 commit comments