UNPKG

gis-tools-ts

Version:

A collection of geospatial tools primarily designed for WGS84, Web Mercator, and S2.

88 lines 2.74 kB
import { createWriteStream } from 'fs'; import { finished } from 'stream/promises'; import { open } from 'fs/promises'; /** The File writer is to be used by bun/node/deno on the local filesystem. */ export class FileWriter { file; #stream; #textEncoder = new TextEncoder(); /** @param file - the location of the PMTiles data in the FS */ constructor(file) { this.file = file; this.#stream = createWriteStream(file, { flags: 'a+' }); // Open with append mode and create stream } /** * Write data to the buffer * @param data - the data to write * @param offset - where in the buffer to start */ async write(data, offset) { const fd = await open(this.file, 'r+'); // Open file for reading and writing try { await fd.write(data, 0, data.length, offset); // Write at the specified offset } finally { await fd.close(); // Close the file after writing } } /** * Append data to the buffer * @param data - the data to append * @returns - a promise that resolves when the data is appended */ async append(data) { return await new Promise((resolve, reject) => { this.#stream.write(data, (err) => { if (err instanceof Error) reject(err); else resolve(); }); }); } /** * Append string to the buffer synchronously * @param string - the string to append */ async appendString(string) { await this.append(this.#textEncoder.encode(string)); } /** * Append data to the buffer synchronously * @param data - the data to append */ appendSync(data) { this.#stream.write(data); // Write data synchronously } /** * Append string to the buffer synchronously * @param string - the string to append */ appendStringSync(string) { this.appendSync(this.#textEncoder.encode(string)); } /** * Slice the buffer * @param start - the start of the slice * @param end - the end of the slice * @returns - the sliced buffer */ async slice(start, end) { const length = end - start; const buffer = Buffer.alloc(length); const fd = await open(this.file, 'r'); try { await fd.read(buffer, 0, length, start); return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); } finally { await fd.close(); } } /** Close the file */ async close() { this.#stream.end(); await finished(this.#stream); } } //# sourceMappingURL=file.js.map