This repository was archived by the owner on Dec 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
110 lines (93 loc) · 2.2 KB
/
Copy pathindex.js
File metadata and controls
110 lines (93 loc) · 2.2 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
98
99
100
101
102
103
104
105
106
107
108
109
110
var fs = require('fs')
, through = require('through3')
, LineStream = require('stream-lines')
, Comment = require('./lib/comment')
, Parser = require('./lib/parser');
/**
* Load and parse file contents.
*
* When a callback function is given it is added as a listener for
* the error and end events on the source file stream.
*
* @function load
* @param {String} file path.
* @param {Object} [opts] processing options.
* @param {Function} [cb] callback function.
*
* @returns the parser stream.
*/
function load(path, opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
opts = opts || {};
opts.highWaterMark = opts.highWaterMark !== undefined
? opts.highWaterMark : 1024;
var source = fs.createReadStream(path)
, lines = new LineStream(opts)
, comment = new Comment(opts)
, parser = new Parser(opts);
parser.file = path;
var stream = source
.pipe(lines)
.pipe(comment)
.pipe(parser);
source.once('error', function onError(err) {
stream.emit('error', err);
if(cb) {
cb(err);
}
});
parser.once('finish', function onFinish() {
source.removeAllListeners();
if(cb) {
cb();
}
});
return stream;
}
/**
* Parse a string or buffer.
*
* When a callback function is given it is added as a listener for
* the error and finish events on the parser stream.
*
* @function parse
* @param {String|Buffer} buffer input data.
* @param {Object} [opts] processing options.
* @param {Function} [cb] callback function.
*
* @returns the parser stream.
*/
function parse(buffer, opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
var Readable = through.passthrough()
, source = new Readable()
, lines = new LineStream(opts)
, comment = new Comment(opts)
, parser = new Parser(opts);
source
.pipe(lines)
.pipe(comment)
.pipe(parser);
if(cb) {
parser
.once('error', cb)
.once('finish', cb);
}
// give callers a chance to listen for events
process.nextTick(function() {
source.end(buffer);
})
return parser;
}
module.exports = {
load: load,
parse: parse,
Comment: Comment,
Parser: Parser
}