Skip to content

Instantly share code, notes, and snippets.

@MichielDeMey
Created July 31, 2017 07:28
Show Gist options
  • Save MichielDeMey/a32b69d23dc05e91b455bdeb757081a1 to your computer and use it in GitHub Desktop.
Save MichielDeMey/a32b69d23dc05e91b455bdeb757081a1 to your computer and use it in GitHub Desktop.
Transform a JSON array using streams
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