Last active
January 23, 2024 17:18
-
-
Save jagenjo/4848c76f4bd41b7490daaa364245c652 to your computer and use it in GitHub Desktop.
Minimal Node+Express+WS App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//minimal node server that opens HTTP and WebSocket ports | |
import path from 'path'; | |
import express from 'express'; //for http request | |
import ExpressWs from 'express-ws' //for websockets | |
import { fileURLToPath } from 'url'; | |
const __filename = fileURLToPath(import.meta.url); | |
const __dirname = path.dirname(__filename); | |
//create express and express websocket router | |
var app = ExpressWs(express()).app; | |
//??? | |
app.use(function (req, res, next) { return next(); }); | |
//app.use(logger('dev')); //to log any HTTP request | |
app.use(express.static(path.join(__dirname, 'public'))); //to serve static files | |
app.get('/', function(req, res, next){ res.end(); }); //?? | |
//on websocket connection, redirect to server | |
app.ws('/', function(ws, req) { | |
console.log("User connected"); | |
ws.on('message', function(msg) { | |
console.log("msg: ", msg) | |
}); | |
ws.on('close', function(msg) { | |
console.log("User left"); | |
}); | |
}); | |
//error handling | |
app.use((err, req, res, next) => { | |
console.log("Error in execution"); | |
console.error(err.stack) | |
res.status(500).send('Error in backend. Something broke!') | |
}) | |
//to capture control C | |
process.on('SIGINT', function() { | |
console.log("Caught interrupt signal"); | |
process.exit(); | |
}); | |
//start listening | |
var port = 3000; | |
console.log("Listening in port " + port) | |
app.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment