-
Notifications
You must be signed in to change notification settings - Fork 46
/
index.ts
212 lines (183 loc) · 5.23 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import archiver from "archiver"
import {execFile} from "child_process"
import {createReadStream} from "fs"
import {tmpdir} from "os"
import {extname, join} from "path"
import {Readable, Stream} from "stream"
type JSONLike = Record<string, unknown>
type RunOutput = {stdout: string; stderr: string}
type Input = string | JSONLike | Stream
interface Result {
cmd: string
text: string
data?: JSONLike
stream?: Readable
extname?: string
details: string
}
type Callback = (err: Error | null, res?: Result) => void
interface Options {
command?: string
format?: string
options?: string[]
destination?: string
env?: Record<string, string>
timeout?: number
maxBuffer?: number
skipFailures?: boolean
}
// Known /vsistdout/ support.
const stdoutRe = /csv|geojson|georss|gml|gmt|gpx|jml|kml|mapml|pdf|vdv/i
const vsiStdIn = "/vsistdin/"
const vsiStdOut = "/vsistdout/"
let uniq = Date.now()
class Ogr2ogr implements PromiseLike<Result> {
private inputStream?: Readable
private inputPath: string
private outputPath: string
private outputFormat: string
private outputExt: string
private customCommand?: string
private customOptions?: string[]
private customDestination?: string
private customEnv?: Record<string, string>
private timeout: number
private maxBuffer: number
private skipFailures: boolean
constructor(input: Input, opts: Options = {}) {
this.inputPath = vsiStdIn
this.outputFormat = opts.format ?? "GeoJSON"
this.customCommand = opts.command
this.customOptions = opts.options
this.customDestination = opts.destination
this.customEnv = opts.env
this.timeout = opts.timeout ?? 0
this.maxBuffer = opts.maxBuffer ?? 1024 * 1024 * 50
this.skipFailures = opts.skipFailures ?? true
let {path, ext} = this.newOutputPath(this.outputFormat)
this.outputPath = path
this.outputExt = ext
if (input instanceof Readable) {
this.inputStream = input
} else if (typeof input === "string") {
this.inputPath = this.newInputPath(input)
} else {
this.inputStream = Readable.from([JSON.stringify(input)])
}
}
exec(cb: Callback) {
this.run()
.then((res) => cb(null, res))
.catch((err) => cb(err))
}
then<TResult1 = Result, TResult2 = never>(
onfulfilled?: (value: Result) => TResult1 | PromiseLike<TResult1>,
onrejected?: (reason: string) => TResult2 | PromiseLike<TResult2>,
): PromiseLike<TResult1 | TResult2> {
return this.run().then(onfulfilled, onrejected)
}
private newInputPath(p: string): string {
let path = ""
let ext = extname(p)
switch (ext) {
case ".zip":
case ".kmz":
case ".shz":
path = "/vsizip/"
break
case ".gz":
path = "/vsigzip/"
break
case ".tar":
path = "/vsitar/"
break
}
if (/^(http|ftp)/.test(p)) {
path += "/vsicurl/" + p
return path
}
path += p
return path
}
private newOutputPath(f: string) {
let ext = "." + f.toLowerCase()
if (stdoutRe.test(this.outputFormat)) {
return {path: vsiStdOut, ext}
}
let path = join(tmpdir(), "/ogr_" + uniq++)
switch (f.toLowerCase()) {
case "esri shapefile":
path += ".shz"
ext = ".shz"
break
case "mapinfo file":
case "flatgeobuf":
ext = ".zip"
break
default:
path += ext
}
return {path, ext}
}
private createZipStream(p: string) {
let archive = archiver("zip")
archive.directory(p, false)
archive.on("error", console.error)
archive.finalize()
return archive
}
private async run() {
let command = this.customCommand ?? "ogr2ogr"
let args = ["-f", this.outputFormat]
if (this.skipFailures) args.push("-skipfailures")
args.push(this.customDestination || this.outputPath, this.inputPath)
if (this.customOptions) args.push(...this.customOptions)
let env = this.customEnv ? {...process.env, ...this.customEnv} : undefined
let {stdout, stderr} = await new Promise<RunOutput>((res, rej) => {
let proc = execFile(
command,
args,
{env, timeout: this.timeout, maxBuffer: this.maxBuffer},
(err, stdout, stderr) => {
if (err) rej(err)
res({stdout, stderr})
},
)
if (this.inputStream && proc.stdin) this.inputStream.pipe(proc.stdin)
})
let res: Result = {
cmd: [command, ...args].join(" "),
text: stdout,
details: stderr,
extname: this.outputExt,
}
if (/^geojson$/i.test(this.outputFormat)) {
try {
res.data = JSON.parse(stdout)
} catch (err) {
// ignore error
}
}
if (!this.customDestination && this.outputPath !== vsiStdOut) {
if (this.outputExt === ".zip") {
res.stream = this.createZipStream(this.outputPath)
} else {
res.stream = createReadStream(this.outputPath)
}
}
return res
}
}
function ogr2ogr(input: Input, opts?: Options): Ogr2ogr {
return new Ogr2ogr(input, opts)
}
ogr2ogr.version = async () => {
let vers = await new Promise<string>((res, rej) => {
execFile("ogr2ogr", ["--version"], {}, (err, stdout) => {
if (err) rej(err)
res(stdout)
})
})
return vers.trim()
}
export default ogr2ogr