Repository navigation
Expand file tree
/
Copy pathreader.js
More file actions
61 lines (51 loc) · 1.42 KB
/
Copy pathreader.js
File metadata and controls
61 lines (51 loc) · 1.42 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
var when = require('when'),
string = require('./string');
var TOKENS = /\s*(,@|[('`,)]|"(?:[\\].|[^\\"])*"|;.*|[^\s('"`,;)]*)(.*)/;
function Reader() {
var port,
buffer = '';
function self() { return self; }
self.port = function(_) {
if(!arguments.length) return _;
port = _;
return self;
}
function next(str) {
var matches = str.match(TOKENS);
buffer = matches[2];
return matches[1];
}
self.nextToken = function() {
return when.iterate(
function(d) { return buffer !== '' ? next(buffer) : readLine().then(next); },
function(d) { return d !== '' && !d.startsWith(';') },
function(d) { buffer = d; },
next(buffer)).catch(function(e){console.log(e)});
}
function readLine() {
var line = '',
deferred = when.defer();
port.resume();
if(port === process.stdin) process.stdout.write('> ');
port.once('data', function(char) {
port.pause();
if(char.contains('\n')) {
var parts = char.split('\n');
deferred.resolve(line + parts.shift());
port.removeAllListeners('end');
port.unshift(parts.join('\n'));
line = '';
} else {
line += char;
port.resume();
}
})
.once('end', function() {
deferred.resolve(line);
});
deferred.promise.catch(function(e){ console.log(e);});
return deferred.promise;
}
return self;
}
module.exports = Reader();