Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created August 31, 2015 18:08
Show Gist options
  • Save mayfer/e1b3c8adf8a4dcdbbed2 to your computer and use it in GitHub Desktop.
Save mayfer/e1b3c8adf8a4dcdbbed2 to your computer and use it in GitHub Desktop.
<!doctype>
<html>
<head>
<title>hi</title>
<style>
body, html {
background: <%= color %>;
font-family: monospace;
}
</style>
</head>
<body>
<% for(var i=0; i<10; i++) { %>
hello <%= message %> <%= i+1 %> <br />
<% } %>
</body>
</html>
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "5.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.13.3",
"http": "0.0.0",
"request": "^2.61.0"
}
}
// now using express to handle routing
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var tools = require('./tools.js');
// attach a middleware
var server = http.Server(app);
app.set("view engine", "ejs");
app.use("/public", express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
var color = tools.getRandomColor();
res.render("index.ejs", { message: "yooooo", color: color, });
});
server.listen(8888, function(){
console.log('listening on *:8888');
});
var http = require("http");
var httprequest = require("request");
var fs = require('fs');
var handleRequest = function(request, response) {
console.log("Request came in", request.url);
var headers = {
"Content-Type": "text/html",
}
if(request.url == "/") {
response.writeHead(200, headers);
response.write("<html><h1>Hello image</h1> <img src='./cat.jpg' /> </html>");
response.end();
} else if(request.url == "/cat.jpg") {
// ??
fs.readFile("./cat.jpg", "binary", function(err, file) {
response.writeHead(200, {
"Content-Type": "image/jpeg",
});
// response.write(file, "binary");
response.end(file, "binary");
});
} else if(request.url == "/google") {
httprequest('http://www.google.com', function (error, httpresponse, body) {
response.writeHead(200, headers);
response.write(body);
response.end();
});
} else {
response.writeHead(404, headers);
response.write("not found");
response.end();
}
}
var app = http.createServer(handleRequest);
app.listen(8081);
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
module.exports = {
getRandomColor: getRandomColor,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment