Zero-dependency Express-like server — interactive demo & reference

Docs & API Reference

Reference for features, options, and API with runnable examples

Quickstart

Run the demo server from the repo root and open http://localhost:3000.

node documentation/full-server.js
# visit http://localhost:3000

Overview

molex-http is a zero-dependency Express-like server with built-in body parsers, streaming multipart uploads, static serving, and a small fetch replacement for Node.

API, Options & Examples

Comprehensive reference for configuration options, runtime behavior, and API examples. Expand each section for details and runnable snippets.
Features
  • Zero-dependency, Express-like API and middleware
  • Built-in parsers: json(), urlencoded(), text(), raw()
  • Streaming multipart uploads with file streaming to disk
  • Static file serving with correct Content-Type handling
  • Small built-in fetch replacement for server-side requests
Server behavior & request model
  • Routing and middleware run in registration order — install parsers before handlers that need parsed bodies.
  • Body parsers populate req.body; multipart uploads populate req.body.files and req.body.fields.
  • Handlers receive req and res objects; use res.json(), res.send() or set status and headers directly.
  • Static middleware serves files with Content-Type derived from extension.
Options (middleware & parser settings)

Common option shapes and defaults for parsers and upload middleware.

Option Type Default Description
json() function Parses JSON bodies into req.body.
urlencoded() function Parses application/x-www-form-urlencoded bodies.
text() function Reads raw text into req.body.
raw() function Reads raw bytes into a Buffer on req.body.
multipart({ dir, maxFileSize }) object { dir: uploadsDir } Streams file parts to disk; exposes req.body.files and req.body.fields.
Type-casting / collapse options (parser-specific)
Option Type Default Notes
explicitArray boolean true When false, single-element arrays are collapsed.
mergeAttrs boolean true Place attributes under the $ key.
typeCast boolean|object true Enable basic casting of numbers/booleans/dates/JSON.
collapseTextNodes boolean false Collapse single text/CDATA-only elements to strings.
API Reference
createApp()

Returns an application instance with Express-like methods: use(), get(), post(), put(), delete(), and listen().

Example
const { createApp, json, static } = require('molex-http')
const app = createApp()

app.use(json({ limit: '10kb' }))
app.get('/', (req, res) => res.send('ok'))
app.listen(3000)
json([opts])

Parses JSON request bodies and populates req.body.

Option Type Default Notes
limit number|string none Maximum body size (bytes or unit string like '1mb').
strict boolean true If true, only accepts objects and arrays; otherwise accepts primitives.
reviver function Optional JSON reviver passed to JSON.parse.
type string|function application/json Mime type matcher for the parser.
Example
// strict JSON parsing with reviver and type matcher
app.use(json({
	limit: '10kb',
	strict: true,
	reviver: (k, v) => {
		// coerce ISO8601-like strings to Date objects
		if (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v)) return new Date(v)
		return v
	},
	type: 'application/json'
}))
urlencoded([opts])

Parses application/x-www-form-urlencoded bodies.

Option Type Default Notes
extended boolean false When true allows rich objects; when false returns simple key/value pairs.
limit number|string none Maximum body size.
type string|function application/x-www-form-urlencoded Mime type matcher.
Example
// parse urlencoded with extended parsing and limit
app.use(urlencoded({ extended: true, limit: '20kb' }))
text([opts])

Reads plain text request bodies into req.body.

Option Type Default Notes
type string|function text/* Mime matcher for which requests are treated as text.
limit number|string none Maximum body size.
encoding string utf8 Character encoding used to decode the incoming bytes.
Example
// accept text/* bodies as UTF-8 with explicit encoding
app.use(text({ type: 'text/*', limit: '50kb', encoding: 'utf8' }))
raw([opts])

Receives raw bytes as a Buffer on req.body.

Option Type Default Notes
type string|function application/octet-stream Mime matcher for raw parser.
limit number|string none Maximum body size.
Example
// receive raw bytes for application/octet-stream
	app.use(raw({ type: 'application/octet-stream', limit: '1mb' }))
multipart({ dir, maxFileSize })

Streaming multipart parser that writes incoming file parts to disk and exposes req.body.files and req.body.fields.

Option Type Default Notes
dir string os.tmpdir() + '/molex-http-uploads' Directory to store uploaded files; can be absolute or relative to process.cwd().
maxFileSize number none Maximum allowed file size in bytes; exceeding this returns 413 and aborts the upload.

Files are stored with a generated name that preserves the original extension when possible; uploaded file metadata is provided in req.body.files.

Example
// stream uploads to disk, limit single file size and set custom dir
app.post('/upload', multipart({ dir: uploadsDir, maxFileSize: 10 * 1024 * 1024 }), (req, res) => {
	// req.body.files contains stored file metadata (originalName, size, path)
	res.json({ files: req.body.files })
})
static(rootPath, opts)

Serves files from a filesystem folder with Content-Type detection and optional caching.

Option Type Default Notes
index string|false 'index.html' File to serve for directory requests.
maxAge number|string 0 Cache-Control max-age (ms or string like '1h').
dotfiles 'allow'|'deny'|'ignore' 'ignore' How to handle dotfiles (e.g., .thumbs).
extensions string[] Fallback extensions to try when a request omits an extension.
setHeaders function Hook to set custom headers per file: (res, filePath) => {}.
Example
// serve UI and hide internal dotfiles, with caching and header hook
app.use(static(path.join(__dirname, 'documentation', 'public'), {
	index: 'index.html',
	dotfiles: 'ignore',
	maxAge: '1h',
	setHeaders: (res, filePath) => { if (filePath.includes('.thumbs')) res.setHeader('X-Internal', '1') }
}))
cors([opts])

Small CORS middleware used in the demo. Typical options:

Option Type Default Notes
origin string|boolean|array '*' Allowed origin(s). Can be a string, false to disable CORS, or an array of origin strings/domains. The middleware will match the request origin against the array internally.
methods string 'GET,HEAD,PUT,POST,DELETE' Allowed methods.
allowedHeaders string Headers allowed in requests.
Example
// allow specific domains and credentials, restrict methods
app.use(cors({ 
	origin: ['https://example.com', 'https://acme.com'], 
	credentials: true, 
	methods: 'GET,POST' 
}))
fetch(url, opts)

Small Node HTTP client returning an object with status, headers and helpers: text(), json(), arrayBuffer(). Supports progress callbacks.

Option Type Notes
method string HTTP method (GET, POST, etc.)
headers object Request headers
body Buffer|string|Stream Request body
timeout number Request timeout in ms
signal AbortSignal Optional AbortSignal to cancel the request (abort)
onUploadProgress function Callback for upload progress: ({loaded, total}) => {}
onDownloadProgress function Callback for download progress.
Example
// GET with timeout and download progress
const r = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
	timeout: 5000,
	onDownloadProgress: ({ loaded, total }) => console.log('download', loaded, total)
})
const data = await r.json()
console.log(data)
Examples

Concise real-world snippets showing how to compose middleware for common tasks.

Small JSON API
const { createApp, json, cors } = require('molex-http')
const app = createApp()

app.use(cors({ origin: ['https://example.com'] }))
app.use(json({ limit: '10kb' }))

const items = []
app.post('/items', (req, res) => {
	items.push(req.body)
  	res.statusCode = 201
  	res.json({ ok: true })
})
Upload handler (disk or custom writer)
// default: stream file parts to disk
app.post('/upload', multipart({ dir: uploadsDir, maxFileSize: 10 * 1024 * 1024 }), (req, res) => {
	// req.body.files contains stored file metadata
  	res.json({ files: req.body.files })
})

// To adapt to S3: replace file write stream in your handler or multipart writer
// with an S3 upload stream and return the remote URL in response.
Serve UI + Protect Internal Uploads
// serve UI
app.use(static(path.join(__dirname, 'documentation', 'public'), { index: 'index.html' }))

// mount uploads but hide internal files like .thumbs
app.use('/uploads', static(path.join(__dirname, 'documentation', 'uploads'), {
	dotfiles: 'ignore',
	setHeaders: (res, filePath) => { if (filePath.includes('.thumbs')) res.setHeader('X-Internal', '1') }
}))
Installation & tests
npm install
# run demo server from repo root
node documentation/full-server.js
# run tests (project-specific)
node test/test.js

Extending

Use the provided middlewares and routing helpers to build controllers, add auth, or swap in different storage backends. The multipart parser exposes file streams and writes each part to disk so you can replace disk writes with S3 streams if desired.

Upload multipart data

Drag, drop or pick a file
Drop files here or
Page 1

Uploaded Files

Thumbnails and metadata
(loading...)

Trash

(loading...)

Quick parser tests


				

Proxy Test


				

This demo doubles as a readable API reference and playground — try uploading files, inspect the returned JSON, and use the playground to test parsers.