forked from pelias/pbf2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (60 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
var util = require('util'),
path = require('path'),
os = require('os'),
split = require('split'),
through = require('through2'),
child = require('child_process'),
exec = path.join(__dirname, 'build', util.format( 'pbf2json.%s-%s', os.platform(), os.arch() ) );
function errorHandler( name ){
return function( data ){
data.toString('utf8').trim().split('\n').forEach( function( line ){
console.log( util.format( '[%s]:', name ), line );
});
};
}
function createReadStream( config ){
var flags = [];
flags.push( util.format( '-tags=%s', config.tags ) );
if( config.hasOwnProperty( 'leveldb' ) ){
flags.push( util.format( '-leveldb=%s', config.leveldb ) );
}
flags.push( config.file );
var proc = child.spawn( exec, flags );
var decoder = createJsonDecodeStream();
proc.stdout
.pipe( split() )
.pipe( through( function( chunk, enc, next ){
var str = chunk.toString('utf8'); // convert buffers to strings
// remove empty lines
if( 'string' === typeof str && str.length ){
this.push( str );
}
next();
}))
.pipe( decoder );
// print error and exit on decoder pipeline error
decoder.on( 'error', errorHandler( 'decoder' ) );
// print error and exit on stderr
proc.stderr.on( 'data', errorHandler( 'pbf2json' ) );
// terminate the process and pipeline
decoder.kill = function(){
proc.kill();
decoder.end();
};
return decoder;
}
function createJsonDecodeStream(){
return through.obj( function( str, enc, next ){
try {
var o = JSON.parse( str );
if( o ){ this.push( o ); }
}
catch( e ){
this.emit( 'error', e );
}
finally {
next();
}
});
}
module.exports.createReadStream = createReadStream;