Created
February 8, 2014 18:51
-
-
Save jpmckinney/8888265 to your computer and use it in GitHub Desktop.
Transform shapefiles to GeoJSON using the node-shp module
This file contains hidden or 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
#!/usr/bin/env node | |
var fs = require('fs') | |
, path = require('path') | |
, walk = require('walk') | |
, shp = require('shp'); | |
if (process.argv.indexOf('--help') !== -1 || process.argv.indexOf('-h') !== -1) { | |
console.log('Usage: geojson.js [input directory] [output directory]'); | |
process.exit(0); | |
} | |
// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions | |
var inDir = process.argv[2] || '.' | |
, outDir = process.argv[3] || path.join(inDir, 'geojson') | |
, pattern = new RegExp('^' + inDir.replace(/[\\^$*+?.()|{}[\]-]/g, '\\$&')) | |
, walker = walk.walk(inDir, { | |
followLinks: false, | |
filters: ['node_modules'] | |
}); | |
walker.on('file', function (root, fileStats, next) { | |
if (fileStats.name.indexOf('.shp', fileStats.name.length - 4) !== -1) { | |
var inFile = path.join(root, fileStats.name.slice(0, -4)) | |
, outFile = path.join(outDir, root. | |
replace(pattern, ''). | |
replace(/^\//, ''). | |
replace(/\//g, '_') + '.geojson') | |
, outStream = fs.createWriteStream(outFile); | |
shp.readFile(inFile, function (err, data) { | |
if (err) { | |
console.error('Error parsing ' + inFile + ':', err); | |
process.exit(1); | |
} | |
else { | |
outStream.write(JSON.stringify(data), function () { | |
console.log(outFile); | |
}); | |
} | |
}); | |
} | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment