|
| 1 | +#!/usr/bin/env node |
| 2 | +// Brief: Builds current DataBase from the MIME-type DB at https://github.com/jshttp/mime-db |
| 3 | +// Argument: [<ref>], optionally provide a reference (branch/tag/commitSHA) to download from, default: latest |
| 4 | + |
| 5 | +import { mkdir, writeFile, link } from 'node:fs/promises'; |
| 6 | + |
| 7 | +const ref = process.argv[2] ?? 'latest'; |
| 8 | + |
| 9 | +// Fetch the DataBase from https://github.com/jshttp/mime-db |
| 10 | +const cdnLink = `https://cdn.jsdelivr.net/gh/jshttp/mime-db@${ref}/db.json`; |
| 11 | +const db = await fetch(cdnLink).then((response) => response.json()); |
| 12 | + |
| 13 | +// Data for Extensions => MIME-type are stored in './extensions' |
| 14 | +await mkdir('./extensions', { recursive: true }); |
| 15 | + |
| 16 | +async function saveMimeData (mimeType) { |
| 17 | + const dir = `./mime-types/${mimeType}`; |
| 18 | + const data = db[mimeType]; |
| 19 | + mkdir(dir, { recursive: true }) |
| 20 | + .then(() => { |
| 21 | + writeFile(`${dir}/data.json`, JSON.stringify(data)); |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +async function saveExtToMime (mimeType) { |
| 26 | + const extensions = db[mimeType].extensions ?? []; |
| 27 | + if (extensions.length === 0) return; |
| 28 | + |
| 29 | + const [first, ...rest] = extensions; |
| 30 | + |
| 31 | + // Write the MIME type to a prototype file, with the first extension, ignore 'EEXIST' errors |
| 32 | + const protoFile = `./extensions/type.${first}`; |
| 33 | + await writeFile(protoFile, mimeType); |
| 34 | + |
| 35 | + // Hard link rest of the extensions to the prototype file, ignore 'EEXIST' errors |
| 36 | + const pending = []; // To hold all pending promises |
| 37 | + for (const extension of rest) { |
| 38 | + pending.push( |
| 39 | + link(protoFile, `./extensions/type.${extension}`) |
| 40 | + .catch((err) => { |
| 41 | + if (err.code !== 'EEXIST') throw err; |
| 42 | + }) |
| 43 | + ); |
| 44 | + } |
| 45 | + return Promise.all(pending); |
| 46 | +} |
| 47 | + |
| 48 | +const pending = []; // To hold all pending promises |
| 49 | +// Loop over all MIME types in the DataBase |
| 50 | +for (const mimeType in db) { |
| 51 | + pending.push( |
| 52 | + saveMimeData(mimeType), |
| 53 | + saveExtToMime(mimeType) |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +await Promise.all(pending); |
| 58 | +console.log(`Built Database from http://github.com/jshttp/mime-db@${ref}`); |
0 commit comments