Node.js高效按行输出文件内容

原创 2016-11-10 14:14:27 530
摘要:const fs = require('fs'); const EventEmitter = require('events'); const util = require('util'); const path = require

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

const fs = require('fs');

const EventEmitter = require('events');

const util = require('util');

const path = require('path');

  

function readFileByLine(file) {

  EventEmitter.call(this);

  file = path.normalize(file);

  this.filePath = file;

  this.lines = [];

  this.initStream();

  this.end = false;

}

  

util.inherits(readFileByLine, EventEmitter);

  

readFileByLine.prototype.initStream = function() {

  let readStream = fs.createReadStream(this.filePath, { encoding: 'utf8' });

  

  readStream.on('data', (data) => {

    this.readStream.pause();

    this.lines = this.lines.concat(data.split(/(?:\n|\r\n|\r)/g));

    this.nextLine();

  });

  

  readStream.on('end', () => {

    this.end = true;

    this.nextLine();

  });

  

  this.readStream = readStream;

};

  

readFileByLine.prototype.nextLine = function() {

  var line;

  

  if (this.end) {

    this.emit('end');

    return ;

  }

  

  if (!this.lines.length) {

    return this.readStream.resume();

  }

  

  line = this.lines.shift();

  line.length && this.emit('line', line);

  

  this.nextLine();

}

接口调用API举例

1

2

3

4

5

6

7

var lr = new readFileByLine('data.txt');

  lr.on('line', (line) => {

   console.log('receive line' + line);

  });

  lr.on('end', () => {

    console.log('end line reader');

  })


发布手记

热门词条