calvinmetcalf/shapefile-js — pull request #26 by pospi (2014-05-26 03:07:46+00:00)
Title: add XMLHttpRequest dependencies to avoid issues when running serverside

This fix was required for the framework to run in a nodejs environment as XMLHttpRequest must be included. Note the fix only solves a crash upon loading, I have run successfully with other workarounds in calling code to avoid broken parameters. Namely:

1. You must load the library as below, since properties are not correctly assigned to the toplevel `shp` function:

shp = require('shpjs'),
shpModule = require.cache[require.resolve('shpjs')],
shpReader = require('shpjs/lib/parseShp'),
proj = shpModule.require('proj4');

2. You'll need to bypass the shapefile loading and do it directly since you're loading a local file and have no `ArrayBuffer` support on the server:

function toArrayBuffer(buffer) {
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}

var inFile = "something.shp",
fs = require('fs'),
projection = proj(/* your WKT transformation string here */);

try {
var buff = new Buffer(fs.readFileSync(inFile)),
aBuff = toArrayBuffer(buff),
shapeData = shpReader(aBuff, projection);
} catch (e) {
// some error in reading the file data
}

// shape data JSON is now stored in `shapeData`.