|
1 | | -import { exec } from 'child_process'; |
| 1 | +import { execFile } from 'child_process'; |
2 | 2 | import fs from 'fs'; |
3 | 3 | import { Readable } from 'stream'; |
4 | 4 | import { pipeline } from 'stream/promises'; |
| 5 | +import { promisify } from 'util'; |
5 | 6 | import config, { getNEDownloadUrl, getNEFilename } from '../config.mjs'; |
6 | 7 |
|
| 8 | +const execFileAsync = promisify(execFile); |
7 | 9 | const { inputDir, resolutions, unDownloadUrl, unFilename, vectors } = config; |
8 | 10 |
|
9 | | -const outputPath = inputDir; |
| 11 | +fs.mkdirSync(inputDir, { recursive: true }); |
10 | 12 |
|
11 | | -// Download Natural Earth vector maps |
| 13 | +/** |
| 14 | + * Download a URL to a file. |
| 15 | + * |
| 16 | + * The function writes to a temporary file and renames it at the end, so a failed download leaves no partial file. |
| 17 | + * |
| 18 | + * @param url - URL to download |
| 19 | + * @param filePath - Path of the output file |
| 20 | + */ |
| 21 | +const download = async (url, filePath) => { |
| 22 | + console.log(`Downloading '${url}'`); |
| 23 | + const response = await fetch(url); |
| 24 | + if (!response.ok || !response.body) throw new Error(`Bad response: ${response.status}`); |
| 25 | + |
| 26 | + const partialFilePath = `${filePath}.part`; |
| 27 | + try { |
| 28 | + await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(partialFilePath)); |
| 29 | + fs.renameSync(partialFilePath, filePath); |
| 30 | + } finally { |
| 31 | + fs.rmSync(partialFilePath, { force: true }); |
| 32 | + } |
| 33 | + const { size } = fs.statSync(filePath); |
| 34 | + const formattedSize = size < 1e6 ? `${(size / 1e3).toFixed(1)} kB` : `${(size / 1e6).toFixed(1)} MB`; |
| 35 | + console.log(`Saved '${filePath}' (${formattedSize})`); |
| 36 | +}; |
| 37 | + |
| 38 | +const extract = async (archivePath) => { |
| 39 | + console.log(`Extracting '${archivePath}'`); |
| 40 | + await execFileAsync('unzip', ['-o', archivePath, '-d', inputDir]); |
| 41 | +}; |
| 42 | + |
| 43 | +// Download and extract Natural Earth vector maps |
12 | 44 | for (const vector of Object.values(vectors)) { |
13 | 45 | for (const resolution of resolutions) { |
14 | | - const url = getNEDownloadUrl({ resolution, vector }); |
15 | 46 | const filename = getNEFilename({ resolution, source: vector.source }); |
16 | | - const archivePath = `${outputPath}/${filename}.zip`; |
17 | | - |
18 | | - if (!fs.existsSync(archivePath)) { |
19 | | - try { |
20 | | - const response = await fetch(url); |
21 | | - if (!response.ok || !response.body) throw new Error(`Bad response: ${response.status}`); |
22 | | - |
23 | | - if (!fs.existsSync(outputPath)) fs.mkdirSync(outputPath, { recursive: true }); |
24 | | - const file = fs.createWriteStream(archivePath); |
25 | | - await pipeline(Readable.fromWeb(response.body), file); |
26 | | - |
27 | | - // Use the shell to handle decompressing |
28 | | - if (!fs.existsSync(outputPath)) fs.mkdirSync(outputPath, { recursive: true }); |
29 | | - exec(`unzip -o ${archivePath} -d ${outputPath}`); |
30 | | - } catch (error) { |
31 | | - console.error(`Error when downloading file '${archivePath}': ${error}`); |
32 | | - continue; |
| 47 | + const archivePath = `${inputDir}/${filename}.zip`; |
| 48 | + try { |
| 49 | + if (fs.existsSync(archivePath)) { |
| 50 | + console.log(`Using the cached archive '${archivePath}'`); |
| 51 | + } else { |
| 52 | + await download(getNEDownloadUrl({ resolution, vector }), archivePath); |
33 | 53 | } |
| 54 | + // Also extract an archive that an earlier run downloaded but did not extract |
| 55 | + if (!fs.existsSync(`${inputDir}/${filename}.shp`)) await extract(archivePath); |
| 56 | + } catch (error) { |
| 57 | + console.error(`Failed to get '${archivePath}': ${error.message}`); |
| 58 | + process.exitCode = 1; |
34 | 59 | } |
35 | 60 | } |
36 | 61 | } |
37 | 62 |
|
38 | | -// Download UN GeoJSON file |
39 | | -const url = unDownloadUrl; |
40 | | -const archivePath = `${outputPath}/${unFilename}.zip`; |
41 | | -const geojsonPath = `${outputPath}`; |
42 | | -const geojsonFilePath = `${geojsonPath}/${unFilename}.geojson`; |
43 | | - |
44 | | -if (fs.existsSync(archivePath)) { |
45 | | - if (!fs.existsSync(geojsonFilePath)) exec(`unzip -o ${archivePath} -d ${geojsonPath}`); |
46 | | -} else { |
47 | | - try { |
48 | | - const response = await fetch(url); |
49 | | - if (!response.ok || !response.body) throw new Error(`Bad response: ${response.status}`); |
50 | | - |
51 | | - const file = fs.createWriteStream(geojsonFilePath); |
52 | | - await pipeline(Readable.fromWeb(response.body), file); |
53 | | - |
54 | | - // Use the shell to handle compression |
55 | | - exec(`zip -j ${archivePath} ${geojsonFilePath}`); |
56 | | - } catch (error) { |
57 | | - console.error(`Error when downloading file '${geojsonFilePath}': ${error}`); |
| 63 | +// Download the UN GeoJSON file, and keep a zipped copy of it as the cache |
| 64 | +const unArchivePath = `${inputDir}/${unFilename}.zip`; |
| 65 | +const unGeojsonPath = `${inputDir}/${unFilename}.geojson`; |
| 66 | +try { |
| 67 | + if (fs.existsSync(unArchivePath)) { |
| 68 | + console.log(`Using the cached archive '${unArchivePath}'`); |
| 69 | + if (!fs.existsSync(unGeojsonPath)) await extract(unArchivePath); |
| 70 | + } else { |
| 71 | + await download(unDownloadUrl, unGeojsonPath); |
| 72 | + console.log(`Saving a zipped copy as the cache at '${unArchivePath}'`); |
| 73 | + await execFileAsync('zip', ['-j', unArchivePath, unGeojsonPath]); |
58 | 74 | } |
| 75 | +} catch (error) { |
| 76 | + console.error(`Failed to get '${unGeojsonPath}': ${error.message}`); |
| 77 | + process.exitCode = 1; |
59 | 78 | } |
| 79 | + |
| 80 | +if (process.exitCode) console.error('Finished with errors. Fix the errors above, then run the script again.'); |
| 81 | +else console.log(`Finished. The geodata is in '${inputDir}'.`); |
0 commit comments