Skip to content

Examples

Alex edited this page Dec 6, 2022 · 6 revisions

HTTPuppy Examples

Serve Static Directory - commonjs

const { useServer } = require('httpuppy');
const server = useServer({
  port: 3001
});

server.static('/', './static-files');

server.start();

Serve Static Directory - ESM/ts

import { useServer } from 'httpuppy';

const server = useServer({
  port: 3000
});
server.static('/static', './static-server-test');

server.start();

Custom Router

import { useServer, useRouter } from 'httpuppy';
const server = useServer({ port: 3000 });
const router = useRouter(server);
router.get('/', (req, res) => res.send({ msg: "Hello World" });
server.start(); 

Custom Router with Static Layer

const { useServer, useRouter } = require('httpuppy');

const app = useServer({
  port: 3000
});

app.static('/', './path/to/content'); //serve arg[1] at the arg[0] href
const router = useRouter(app);
router.get('/api/v1/content', (req, res) => res.json({msg: "success"}));
app.start();

the static method is a promise so that it can crawl the filesystem using generators, the code for that is here

Custom Router with Middleware

import { useServer, useRouter } from 'httpuppy';
const server = useServer({ port: 3000 });
const router = useRouter(server);
router.get('/', (req, res) => res.send({ msg: "Hello World" });
router.use('/', (req, res) => console.log(req.url));
server.start(); 

Dynamic Routing

router.get('/:route', (req, res) => res.send({ msg: req.params.route });

clustered mode

clustered mode will allow your server to utilize multiple cores available on your system to speed up your requests. If you'd like to enable this, make sure to set clustered: true in your config, programmatic or cli it will be available.

const app = useServer({
	...
	clustered: true
	...
});

handling form data

const { useServer, useRouter } = require('httpuppy');

const app = useServer({
	...
});

const router = useRouter(app);

router.post('/api/v1/thing', (req, res) => {
	console.log(req.body) // json format: { foo: 'bar' }
	// do something with body and respond
});

app.start();

async support

const { useServer, useRouter } = require('httpuppy');

const app = useServer({
	port: 3000
});
const router = useRouter(app);

router.post('/api/v1/thing', async(req, res) => {
	// await something
	console.log(req.body) // json format: { foo: 'bar' }
	// do something with body and respond
});

app.start();