random-img-api
v0.1.2
Published
Serve random images from local directory
Downloads
25
Readme
random-img-api
A small HTTP API that serves a random local image from a category directory. Built with Node.js, TypeScript, and Hono.
Features
- Serves a random image from
images/<category> - Validates category names to reduce path traversal risk
- Verifies files are actual supported images before returning them
- Supports CLI flags and environment variables for runtime config
- Emits simple console logs for startup, requests, and shutdown
Requirements
- Node.js 22+
- pnpm 10+ recommended
Installation
pnpm installDirectory Layout
Images are loaded from the configured image root directory. By default that is ./images.
Example:
images/
cats/
cat-1.jpg
cat-2.png
dogs/
dog-1.webpDevelopment
Start the server directly from TypeScript:
pnpm devWith custom options:
pnpm dev -- --host 0.0.0.0 --port 8080 --images-dir ./imagesBuild
pnpm buildAfter building, run the compiled binary:
node dist/index.mjsAPI
GET /random-image/:category
Returns one random image from the matching category directory.
Example:
curl -o random.jpg http://127.0.0.1:3000/random-image/catsPossible responses:
200with image content400 Invalid category404 Category not found404 No images available404 No valid images available500 Internal server error
CLI Options
--host <host> Host to bind to
--port <port> Port to listen on
--images-dir <path> Root directory containing image categories
--help, -h Show helpDefaults:
host:127.0.0.1port:3000images-dir:<project>/images
Environment Variables
CLI flags can also be provided through environment variables:
HOSTPORTIMAGES_DIR
CLI flags take precedence over environment variables.
Security Notes
- Category names only allow letters, numbers,
_, and- - Category paths are resolved and checked to stay inside the configured image root
- Only regular files are considered
- Returned responses include
X-Content-Type-Options: nosniff - Images are inspected before being served instead of trusting file extensions alone
License
MIT
