]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.maps.server/node/node-v4.8.0-win-x64/node_modules/npm/node_modules/ansi/lib/newlines.js
Adding integrated tile server
[simantics/district.git] / org.simantics.maps.server / node / node-v4.8.0-win-x64 / node_modules / npm / node_modules / ansi / lib / newlines.js
1
2 /**
3  * Accepts any node Stream instance and hijacks its "write()" function,
4  * so that it can count any newlines that get written to the output.
5  *
6  * When a '\n' byte is encountered, then a "newline" event will be emitted
7  * on the stream, with no arguments. It is up to the listeners to determine
8  * any necessary deltas required for their use-case.
9  *
10  * Ex:
11  *
12  *   var cursor = ansi(process.stdout)
13  *     , ln = 0
14  *   process.stdout.on('newline', function () {
15  *    ln++
16  *   })
17  */
18
19 /**
20  * Module dependencies.
21  */
22
23 var assert = require('assert')
24 var NEWLINE = '\n'.charCodeAt(0)
25
26 function emitNewlineEvents (stream) {
27   if (stream._emittingNewlines) {
28     // already emitting newline events
29     return
30   }
31
32   var write = stream.write
33
34   stream.write = function (data) {
35     // first write the data
36     var rtn = write.apply(stream, arguments)
37
38     if (stream.listeners('newline').length > 0) {
39       var len = data.length
40         , i = 0
41       // now try to calculate any deltas
42       if (typeof data == 'string') {
43         for (; i<len; i++) {
44           processByte(stream, data.charCodeAt(i))
45         }
46       } else {
47         // buffer
48         for (; i<len; i++) {
49           processByte(stream, data[i])
50         }
51       }
52     }
53
54     return rtn
55   }
56
57   stream._emittingNewlines = true
58 }
59 module.exports = emitNewlineEvents
60
61
62 /**
63  * Processes an individual byte being written to a stream
64  */
65
66 function processByte (stream, b) {
67   assert.equal(typeof b, 'number')
68   if (b === NEWLINE) {
69     stream.emit('newline')
70   }
71 }