UNPKG

microsite

Version:
33 lines (32 loc) 1.24 kB
import _fetch, { Response, FetchError } from "node-fetch"; import { resolve } from 'path'; import { promises as fsp } from 'fs'; import { readDir } from "../utils/fs.js"; const cwd = import.meta.url.slice('file:/'.length).split('node_modules')[0].slice(0, -1); async function fetch(url, init) { if (typeof url === 'string' && !url.startsWith('http')) { url = resolve(cwd, `.${url}`); try { const stat = await fsp.stat(url); if (stat.isFile()) { const content = await fsp.readFile(url, 'utf-8'); return new Response(content); } else if (stat.isDirectory()) { let contents = await readDir(url); contents = contents.map(path => path.slice(url.length)); const res = new Response(JSON.stringify(contents)); res.headers.set('Content-Type', 'application/json'); return res; } } catch (e) { const err = new FetchError(`Unable to fetch ${url}. ${e.message}`); err.code = 'ERR_NOT_FOUND'; err.errno = '404'; throw err; } } return _fetch(url, init); } export default fetch;