s2-tools
Version:
A collection of geospatial tools primarily designed for WGS84, Web Mercator, and S2.
48 lines • 1.95 kB
JavaScript
import { DataBaseFile } from './dbf';
import { MMapReader } from '../mmap';
import { ShapeFileReader } from './shp';
import { Transformer } from '../../proj4';
import { shapefileFromGzip } from '.';
import { exists, readFile } from 'fs/promises';
export * from './dbf';
export * from './shp';
/**
* Assumes the input is pointing to a shapefile or name without the extension.
* The algorithm will find the rest of the paths if they exist.
* @param input - the path to the .shp file or name without the extension
* @returns - a Shapefile
*/
export async function shapefileFromPath(input) {
if (input.endsWith('.zip')) {
const gzipData = await readFile(input);
return shapefileFromGzip(gzipData.buffer);
}
const path = input.replace('.shp', '');
const shp = `${path}.shp`;
const dbf = `${path}.dbf`;
const prj = `${path}.prj`;
const cpg = `${path}.cpg`;
if (!(await exists(shp)))
throw new Error('Shapefile does not exist');
const definition = {
shp,
dbf: (await exists(dbf)) ? dbf : undefined,
prj: (await exists(prj)) ? prj : undefined,
cpg: (await exists(cpg)) ? cpg : undefined,
};
return shapefileFromDefinition(definition);
}
/**
* Build a Shapefile from a Definition
* @param def - a description of the data to parse
* @returns - a Shapefile
*/
export async function shapefileFromDefinition(def) {
const { shp, dbf, prj, cpg } = def;
const encoding = cpg !== undefined ? await readFile(cpg, { encoding: 'utf8' }) : 'utf8';
const transform = prj !== undefined ? new Transformer(await readFile(prj, { encoding: 'utf8' })) : undefined;
const dbfReader = dbf !== undefined ? new MMapReader(dbf) : undefined;
const databaseFile = dbfReader !== undefined ? new DataBaseFile(dbfReader, encoding) : undefined;
return new ShapeFileReader(new MMapReader(shp), databaseFile, transform);
}
//# sourceMappingURL=mmap.js.map