Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var http = require('http')
- , fs = require('fs')
- , url = require('url')
- , path = require('path')
- // Goal: get this to client
- var classes = ['cs573', 'cs4241']
- var filtered = ['cs573', 'cs4241']
- var server = http.createServer (function (req, res) {
- var uri = url.parse(req.url);
- console.log(uri.pathname);
- switch( uri.pathname ) {
- case '/':
- sendFile(res, 'public/index.html', 'text/html');
- break;
- case '/index.html':
- sendFile(res, 'public/index.html', 'text/html');
- break;
- case '/css/main.css':
- sendFile(res, 'public/css/main.css', 'text/css');
- console.log('sent css!');
- break;
- case '/add':
- console.log('Add!')
- handleAdd(req);
- res.end('done adding');
- break;
- case '/del':
- console.log('Del!');
- handleDel(req);
- res.end('done deleting');
- break;
- case '/filter':
- console.log('Filter!');
- handleFilter(req);
- res.end('done filtering');
- break;
- case '/list':
- res.end( JSON.stringify(filtered) );
- break;
- default:
- res.end('404 not found');
- }
- });
- function applyFilter(filter) {
- // filtering
- filtered.length = 0;
- for (var i=0; i<classes.length; i++) {
- console.log('About to filter');
- console.log(classes[i]);
- console.log(filter);
- if (classes[i].toLowerCase().search(filter.toLowerCase()) != -1) {
- console.log('match');
- filtered.push(classes[i]);
- };
- }
- }
- function handleAdd(req) {
- var chunk = ""
- req.on('data', function(data) {
- chunk += data;
- })
- req.on('end', function(data) {
- // Note: this is not a great way to access this object.
- var obj = chunk.split('=');
- classes.push( obj[1] );
- applyFilter("");
- })
- }
- function handleDel(req) {
- // remove the given class from list
- var chunk = ""
- req.on('data', function(data) {
- chunk += data;
- })
- req.on('end', function(data) {
- // Note: this is not a great way to access this object.
- var obj = chunk.split('=');
- //classes.push( obj[1] );
- var index = classes.indexOf(obj[1]);
- classes.splice(index, 1);
- applyFilter("");
- })
- }
- function handleFilter(req) {
- // remove the given class from list
- var chunk = ""
- req.on('data', function(data) {
- chunk += data;
- })
- req.on('end', function(data) {
- // Note: this is not a great way to access this object.
- var filter = chunk.split('=')[1];
- applyFilter(filter);
- });
- }
- server.listen(8080);
- console.log('listening on 8080');
- // subroutines
- function sendFile(res, filename, contentType) {
- res.writeHead(200, {'Content-type': contentType })
- var stream = fs.createReadStream(filename)
- stream.on('data', function(data) {
- res.write(data);
- })
- stream.on('end', function(data) {
- res.end();
- return;
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement