retra

The powerful, lightweight HTTP server library for Node

Usage no npm install needed!

<script type="module">
  import retra from 'https://cdn.skypack.dev/retra';
</script>

README

The powerful, lightweight HTTP server library for Node

GitHub | NPM

Contents

Install

npm i retra

And then use it!

const Retra = require('retra')

Usage

Create a server

const app = new Retra()

Add a simple handler for GET requests

app.add('GET', '/test', (req, res) => {
    res.status(200).body('Hey there!').end()
})

Read query string parameters from requests

app.add(/* ? ... ? */(req, res) => {
    console.log('name=' + res.query('name'))

    // This logs the query string property 'name' from the request.
})

Parse request as JSON

app.add(/* ? ... ? */ async (req, res) => {
    const parsed = await req.json()

    res.body({
        'yourName': parsed.name
    }).end()
})

Set response headers

Setting one header:

app.add(/* ? ... ? */ (req, res) => {
    res.header('content-type', 'squid').end()
})

Setting many at once:

app.add(/* ? ... ? */ (req, res) => {
    res.header({
        'content-type': 'squid',
        'x-server': 'retra'
    }).end()
})

Handle all POST requests to any path

app.add('POST', (req, res) => {
    // ...
})

Handle requests using any method to path /squid

app.add('/squid', (req, res) => {
    // ...
})

Stream a response

// ... require fs, path

app.add('/stream', (req, res) => {
    res.coreRes.pipe(fs.createReadStream(path.join(__dirname, 'test.txt')))
})

Make your server listen on port 8080

app.listen(8080, () => {
    console.log('Listening!')
})

Listen as an HTTPS server

// ... require https

https.createServer(app.externalHandler).listen(443)

Handle route errors

app.on('routeError', (err, req, res) => {
    if (res.coreRes.finished === false) {
        res.writeHead(500)
        res.end({
            'error': err.message
        })
    }

    // This will respond with the error when one occurs!
})

Official extensions

retra-static

Host static files in your retra server, easily and efficiently.

GitHub | NPM

Install:

npm i retra-static

Use:

// ... require path module
const static = require('retra-static')

app.use(static(path.join(__dirname, 'static')))

// This will host from the /static directory!