-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·81 lines (68 loc) · 1.74 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env node
_ = require('lodash');
var argv = require('minimist')(process.argv.slice(2));
defaults = {
milliseconds:300,
"max-queue":1000,
queue:true
};
argv = _.merge(defaults,argv)
if (argv.m)
argv.milliseconds=argv.m;
if (argv.q)
argv.queue=argv.q;
if (argv.x)
argv["max-queue"]=argv.x;
process.stdin.resume();
process.stdin.setEncoding('utf8');
var lingeringLine = "";
var Throttler = function(options){
var lastTime=0;
var self=this;
this.lines=[];
this.finished=false;
this.finish=function(){
this.finished=true;
checkFinished();
}
this.pushLine=function(line){
if (self.lines.length<argv["max-queue"])
this.lines.push(line);
}
var checkFinished=function(){
if (self.lines.length==0 && self.finished) {
process.exit(0);
}
}
var processLine=function(){
if (self.lines.length==0) {
checkFinished();
return false;
}
var currentTime = new Date();
if (+lastTime+argv.milliseconds<+currentTime) {
lastTime=new Date();
console.log(self.lines[0]);
self.lines.shift();
if(options.queue==false)
self.lines=[];
return true;
}
return false;
}
setInterval(processLine, 10);
}
throttler = new Throttler(argv);
process.stdin.on('data', function(chunk) {
var lines=chunk.split("\n");
lines[0] = lingeringLine + lines[0];
lingeringLine = lines.pop();
lines.forEach(function(line){
throttler.pushLine(line);
});
});
process.stdin.on('end', function() {
if(lingeringLine.length>0)
throttler.pushLine(lingeringLine);
throttler.finish();
});