-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
97 lines (78 loc) · 2.03 KB
/
index.js
File metadata and controls
97 lines (78 loc) · 2.03 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* jslint laxbreak: true */
'use strict';
var type = require('utils-type');
var monkey = require('stdout-monkey')();
var track = require('callers-module');
var batch = { };
var wait = require('./lib/wait');
var store = require('./lib/store');
var origin = require('./lib/origin');
var filter = require('./lib/filter');
var debug = require('./lib/debug');
var write = require('./lib/write');
// it can happen
process.once('exit', function(){
var sink;
if(batch.data){
sink = !debug.DEBUG || console.log('exit', batch);
write(batch, monkey);
}
});
// exports.these
function these(chunk, callback){
callback = type(callback).function;
var caller = track(callback ? these : origin());
batch.path = batch.path || caller.path;
batch.module = batch.module || caller.module;
batch.location = batch.location || caller.location;
if( batch.timer ){
clearTimeout(batch.timer);
delete batch.timer;
}
var waiting = callback
? filter(batch, caller)
: batch.module === caller.module;
if( waiting ){
batch.path = caller.path;
batch.module = caller.module;
batch.location = caller.location;
batch.handle = callback;
debug('waiting...', batch);
} else {
debug('direct write', batch);
write(batch, monkey, debug);
batch = {
path : caller.path,
module : caller.module,
location : caller.location,
handle : callback
};
}
// so callbacks can store data differently
if( callback ){
store(batch, chunk);
} else {
batch.data = batch.data || [ ];
batch.data.push(chunk);
}
// keep a timer anyway
batch.timer = setTimeout(function(){
if( batch.data ){
debug('timer kicks', batch);
write(batch, monkey);
batch = { };
}
}, wait());
return exports;
}
// patch stdout with the batched version
monkey.patch(these);
// It would make more sense to have a class
// but for `stdout`... is kind of weird somehow
module.exports = {
wait : wait,
origin : origin,
filter : filter,
these : these,
store : store
};