Websocket
[VSoRC/.git] / node_modules / websocket / lib / utils.js
1 var noop = exports.noop = function(){};
2
3 exports.extend = function extend(dest, source) {
4     for (var prop in source) {
5         dest[prop] = source[prop];
6     }
7 };
8
9 exports.eventEmitterListenerCount =
10     require('events').EventEmitter.listenerCount ||
11     function(emitter, type) { return emitter.listeners(type).length; };
12
13 exports.bufferAllocUnsafe = Buffer.allocUnsafe ?
14     Buffer.allocUnsafe :
15     function oldBufferAllocUnsafe(size) { return new Buffer(size); };
16
17 exports.bufferFromString = Buffer.from ?
18     Buffer.from :
19     function oldBufferFromString(string, encoding) {
20       return new Buffer(string, encoding);
21     };
22
23 exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) {
24     var logFunction = require('debug')(identifier);
25     if (logFunction.enabled) {
26         var logger = new BufferingLogger(identifier, uniqueID, logFunction);
27         var debug = logger.log.bind(logger);
28         debug.printOutput = logger.printOutput.bind(logger);
29         debug.enabled = logFunction.enabled;
30         return debug;
31     }
32     logFunction.printOutput = noop;
33     return logFunction;
34 };
35
36 function BufferingLogger(identifier, uniqueID, logFunction) {
37     this.logFunction = logFunction;
38     this.identifier = identifier;
39     this.uniqueID = uniqueID;
40     this.buffer = [];
41 }
42
43 BufferingLogger.prototype.log = function() {
44   this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]);
45   return this;
46 };
47
48 BufferingLogger.prototype.clear = function() {
49   this.buffer = [];
50   return this;
51 };
52
53 BufferingLogger.prototype.printOutput = function(logFunction) {
54     if (!logFunction) { logFunction = this.logFunction; }
55     var uniqueID = this.uniqueID;
56     this.buffer.forEach(function(entry) {
57         var date = entry[0].toLocaleString();
58         var args = entry[1].slice();
59         var formatString = args[0];
60         if (formatString !== (void 0) && formatString !== null) {
61             formatString = '%s - %s - ' + formatString.toString();
62             args.splice(0, 1, formatString, date, uniqueID);
63             logFunction.apply(global, args);
64         }
65     });
66 };