Skip to content

Instantly share code, notes, and snippets.

@anak10thn
Forked from porsager/README.md
Created March 2, 2023 12:40
Show Gist options
  • Save anak10thn/40f330b79aca2acce2e345fe3a54b7c2 to your computer and use it in GitHub Desktop.
Save anak10thn/40f330b79aca2acce2e345fe3a54b7c2 to your computer and use it in GitHub Desktop.
A websocket middleware for express

A websocket middleware for express

A convenient way to expose a websocket connections in route handles.

Usage

const express = require('express')
    , ws = require('./ws')

const app = express()

app.get('/', (req, res) => 
  req.ws
    ? res.ws(socket => /* do something with the socket */ )
    : res.send('Hello you non websocket')
)

app.listen(PORT)

server.on('upgrade', ws(app))
const uws = require('uws')
, http = require('http')
const wss = new uws.Server({ noServer: true })
module.exports = app => (req, socket, head) => {
const res = new http.ServerResponse(req)
res.assignSocket(socket)
res.on('finish', () => res.socket.destroy())
req.ws = true
res.ws = fn => wss.handleUpgrade(req, socket, head, fn)
app(req, res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment