-
Notifications
You must be signed in to change notification settings - Fork 0
/
OsmiumStream.js
84 lines (70 loc) · 1.94 KB
/
OsmiumStream.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
82
83
84
var util = require('util'),
osmium = require('osmium'),
Readable = require('readable-stream');
function OsmiumStream( reader ){
Readable.call( this, { objectMode: true } );
this._reader = reader;
this._internalBuffer = [];
}
util.inherits( OsmiumStream, Readable );
OsmiumStream.osmium = osmium;
OsmiumStream.prototype._flush = function(){
var flooding = false;
while( !flooding ){
var item = this._internalBuffer.shift();
if( !item ){ return true; }
flooding = !!this.push( item );
if( flooding ){ return false; }
}
return true;
};
OsmiumStream.prototype._next = function(){
// wait for drain
if( !this._flush() ){ return; }
var buffer = this._reader.read();
// end of file
if( !buffer ){ return this._end(); }
this._extractBuffer( buffer, [], function( extracted ){
this._internalBuffer = this._internalBuffer.concat( extracted );
this._next();
}.bind(this));
};
OsmiumStream.prototype._mapRecord = function( object ){
if( object instanceof osmium.Node ){
return {
type: 'node',
id: object.id,
lat: object.lat,
lon: object.lon,
tags: object.tags()
};
} else if( object instanceof osmium.Way ){
return {
type: 'way',
id: object.id,
refs: object.node_refs(),
tags: object.tags()
};
} else if( object instanceof osmium.Relation ){
return {
type: 'relation',
id: object.id
};
} else {
console.log( 'unkown type', object.constructor.name );
return null;
}
};
OsmiumStream.prototype._end = function(){
this.push( null );
};
OsmiumStream.prototype._extractBuffer = function( buffer, extracted, done ){
var object = buffer.next();
if( !object ){ return done( extracted ); } //done
else { extracted.push( this._mapRecord( object ) ); }
setImmediate( this._extractBuffer.bind( this, buffer, extracted, done ) );
};
OsmiumStream.prototype._read = function(){
this._next();
};
module.exports = OsmiumStream;