Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lab submission #225

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
}
]
}
72 changes: 72 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const express = require('express');
const path = require('path');
const EventEmitter = require('events');

const port = process.env.PORT || 3000;
const chatEmitter = new EventEmitter();

function respondText(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.end('hi');
}

function respondJson(req, res) {
res.json({
text: 'hi',
numbers: [
1, 2, 3
],
});
}

function respondNotFound(req, res) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}

function respondEcho(req, res) {
const { input = '' } = req.query;

res.json({
normal: input,
shouty: input.toUpperCase(),
charCount: input.length,
backwards: input.split('').reverse().join(''),
});
}

function chatApp(req, res) {
res.sendFile(path.join(__dirname, '/chat.html'));
}

function respondChat (req, res) {
const { message } = req.query;

chatEmitter.emit('message', message);
res.end();
}

function respondSSE (req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
});

const onMessage = message => res.write(`data: ${message}\n\n`);

chatEmitter.on('message', onMessage);
res.on('close', () => {
chatEmitter.off('message', onMessage);
});
}

const app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', chatApp);
app.get('/chat', respondChat);
app.get('/sse', respondSSE);


app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Loading