-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (57 loc) · 1.67 KB
/
index.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* eslint: handle-callback-err: 0 */
/*
** USAGE:
**
** const Debussy = require('debussy');
** const FileReader = new Debussy('path/to/filename');
**
** // or pass in options to override defaults.
** // refer to fs.createReadStream() documentation.
** const FileReader = new Debussy(filename, {encoding: 'utf-8'});
**
** FileReader.on('line', line => {
** // process line...
**
** // found what you need; stop the stream.
** FileReader.stop();
** });
**
** FileReader.on('end', () => {
** // do something after last line has been read...
** });
**
** The MIT License (MIT)
** Copyright (c) 2016-Eternity Gerry Gold
**/
const fs = require('fs');
const readline = require('readline');
const EventEmitter = require('events').EventEmitter;
class Debussy extends EventEmitter {
constructor(filename, userOptions = {}) {
super();
// Based on: https://nodejs.org/api/fs.html
const defaultCreateReadStreamOptions = {
flags: 'r',
encoding: null,
fd: null,
mode: 0o666,
autoClose: true
};
const mergedOptions = {};
Object.assign(mergedOptions, defaultCreateReadStreamOptions, userOptions);
this.inputStream = fs.createReadStream(filename, mergedOptions);
const rd = readline.createInterface({
input: this.inputStream,
output: process.stdout,
terminal: false
});
rd.on('line', line => this.emit('line', line));
rd.on('close', () => this.emit('end'));
}
stop() {
// destroy() marks the object as destroyed and then calls close()
// Based on: https://github.com/nodejs/node/blob/master/lib/fs.js
this.inputStream.destroy();
}
}
module.exports = Debussy;