1 | var fs = require('fs'),
|
2 | EventEmitter = require('events').EventEmitter,
|
3 | util = require('util');
|
4 |
|
5 | var readLine = module.exports = function(file, opts) {
|
6 | if (!(this instanceof readLine)) return new readLine(file);
|
7 |
|
8 | EventEmitter.call(this);
|
9 | opts = opts || {};
|
10 | opts.maxLineLength = opts.maxLineLength || 4096;
|
11 | var self = this,
|
12 | lineBuffer = new Buffer(opts.maxLineLength),
|
13 | lineLength = 0,
|
14 | lineCount = 0,
|
15 | byteCount = 0,
|
16 | emit = function(lineCount, byteCount) {
|
17 | try {
|
18 | self.emit('line', lineBuffer.slice(0, lineLength).toString(), lineCount, byteCount);
|
19 | } catch (err) {
|
20 | self.emit('error', err);
|
21 | } finally {
|
22 | lineLength = 0;
|
23 | }
|
24 | };
|
25 | this.input = ('string' === typeof file) ? fs.createReadStream(file, opts) : file;
|
26 | this.input.on('open', function(fd) {
|
27 | self.emit('open', fd);
|
28 | })
|
29 | .on('data', function(data) {
|
30 | for (var i = 0; i < data.length; i++) {
|
31 | if (data[i] == 10 || data[i] == 13) {
|
32 | lineCount++;
|
33 | if (lineLength) emit(lineCount, byteCount);
|
34 | } else {
|
35 | lineBuffer[lineLength] = data[i];
|
36 | lineLength++;
|
37 | }
|
38 | byteCount++;
|
39 | }
|
40 | })
|
41 | .on('error', function(err) {
|
42 | self.emit('error', err);
|
43 | })
|
44 | .on('end', function() {
|
45 |
|
46 | if (lineLength) {
|
47 | lineCount++;
|
48 | emit(lineCount, byteCount);
|
49 | }
|
50 | self.emit('end');
|
51 | })
|
52 | .on('close', function() {
|
53 | self.emit('close');
|
54 | });
|
55 | };
|
56 | util.inherits(readLine, EventEmitter);
|