Created
July 31, 2017 07:28
-
-
Save MichielDeMey/a32b69d23dc05e91b455bdeb757081a1 to your computer and use it in GitHub Desktop.
Transform a JSON array using streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const transfuse = require('transfuse') | |
const stationsStream = fs.createReadStream('./stations.json') | |
const geoJSONStream = fs.createWriteStream('./stations.geojson', { autoClose: false }) | |
const stationTransformer = transfuse((doc, map) => { | |
if (doc.lng > 180.0 || doc.lng < -180.0 || | |
doc.lat > 90.0 || doc.lat < -90.0) { | |
console.log('malformed location', doc.naam) | |
return map() | |
} | |
map({ | |
type: 'Feature', | |
properties: { | |
name: doc.naam | |
}, | |
geometry: { | |
type: 'Point', | |
coordinates: [ | |
doc.lng, | |
doc.lat | |
] | |
} | |
}); | |
}); | |
// Header | |
geoJSONStream.write('{"type": "FeatureCollection", "features": ', 'utf8') | |
// Footer | |
// (nothing more to read from the stationsStream, end the writer) | |
stationTransformer.on('end', () => { | |
geoJSONStream.write('}', 'utf8') | |
geoJSONStream.end() | |
}) | |
stationsStream | |
.pipe(stationTransformer) | |
.pipe(geoJSONStream, { end: false }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment