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

Code Submission #248

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
76 changes: 76 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@

const express = require('express');
const path = require('path');

const port = process.env.PORT || 3000;
const EventEmitter = require('events');

const chatEmitter = new EventEmitter();

function respondText(req, res) {
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('/sse', respondSSE);

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




Loading