-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreamReader.js
73 lines (65 loc) · 1.72 KB
/
StreamReader.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
68
69
70
71
72
73
/**
* Credit: Matt Butcher
* URL: http://technosophos.com/2012/10/19/using-string-stream-reader-nodejs.html
*
*/
// Core libraries we will use:
var util = require('util');
var Stream = require('stream');
var Buffer = require('buffer').Buffer;
/*
* A Readable stream for a string or Buffer.
*
* This works for both strings and Buffers.
*/
function StringReader(str) {
this.data = str;
}
// Make StringReader a Stream.
util.inherits(StringReader, Stream);
module.exports = StringReader;
/*
* This is more important than it may look. We are going to
* create a "stream" that is "paused" by default. This gives
* us plenty of opportunity to pass the reader to whatever
* needs it, and then `resume()` it.
*
* This will do the following things:
* - Emit the (entire) string or buffer in one chunk.
* - Emit the `end` event.
* - Emit the `close` event.
*/
StringReader.prototype.resume = function () {
// If the data is a buffer and we have an encoding (from setEncoding)
// then we convert the data to a String first.
if (this.encoding && Buffer.isBuffer(this.data)) {
this.emit('data', this.data.toString(this.encoding));
}
// Otherwise we just emit the data as it is.
else {
this.emit('data', this.data);
}
// We emitted the entire string, so we can finish up by
// emitting end/close.
this.emit('end');
this.emit('close');
}
/*
* Set the encoding.
*
* This is used for Buffers.
*/
StringReader.prototype.setEncoding = function (encoding) {
this.encoding = encoding;
}
/*
* This is here for API completeness, but it does nothing.
*/
StringReader.prototype.pause = function () {
}
/*
* This is here for API completeness.
*/
StringReader.prototype.destroy = function () {
delete this.data;
}