@jadiewadie/simple-server v2.3.3
simple-server
A simple HTTP/s server, built using express
Installation
Install with NPM.
npm install @jadiewadie/simple-server
Usage
To create a server, use the Server
constructor. Then, call server.start
with a port.
const server = new Server();
await server.start(3000);
Configuration
HTTPS
The https
object is provided to https.createServer()
.
const server = new Server({
https: {
key: readFileSync('privkey.pem'),
cert: readFileSync('cert.pem'),
ca: readFileSync('chain.pem')
}
});
await server.start(3000);
It can also generate a self-signed certificate.
const server = new Server({
https: true
});
await server.start(3000);
API
Route Definition
Routes are defined as follows:
Field | Value |
---|---|
verb | The HTTP verb of the route. |
name | The name of the route. This can include url parameters, such as /user/:id . |
call | The callback for the route, taking req , res and next as arguments. |
Route Loading
A list of routes can be provided to the api
option. The prefix
option is also available.
const server = new Server({
api: {
prefix: '/api',
routes: [
{
verb: 'get',
name: '/ping',
call: (req, res) => res.send('Pong!')
},
{
verb: 'get',
name: '/hello/:name',
call: (req, res) => res.send(`Hello ${req.params.name}!`)
}
]
}
});
Alternatively, routes can be loaded recursively from a folder. The strict
flag indicates whether invalid files should throw an error (true
) or be ignored (false
).
const server = new Server({
api: {
routes: {
folder: path.join(__dirname, 'api'),
load: async filename => (await import(filename)).default,
strict: true
}
}
});
The recursive getFiles
function can be used for custom route loading.
import { getFiles } from '@jadiewadie/simple-server';
getFiles(path.join(__dirname, 'api')); // An array of paths
Statics
A list of directories to serve as statics can be provided to statics
. The strict
flag indicates whether invalid paths should throw an error (true
) or be ignored (false
).
const server = new Server({
statics: {
paths: [path.join(__dirname, 'public')],
strict: true
}
});
Folder paths can be passed alongside prefixes. For example, hosting the data
folder at the /data
route.
const server = new Server({
statics: {
paths: [
{
prefix: '/data',
folder: [path.join(__dirname, 'data')]
}
]
}
});
CORS
The cors
object is provided as configuration to the cors package.
const server = new Server({
cors: {
origin: 'http://localhost:3000'
}
});
Error Handling
Error handlers can be provided to error
and api.error
.
const server = new Server({
error: (req, res) => res.redirect('/404.html'),
api: {
error: (req, res) => res.redirect('/404-api.html')
}
});