Skip to content

Commit

Permalink
Created simplistic Node.js web server
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeff Gold committed Jul 6, 2015
1 parent 9ab6f06 commit 415c918
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*~
4 changes: 4 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<!DOCTYPE html>
<title>RaspberryPi Server</title>
<h1>RaspberryPi Server</h1>
<p>This page is being served from a RaspberryPi</p>
4 changes: 4 additions & 0 deletions page404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<!DOCTYPE html>
<title>Page Not Found: :PATH:</title>
<h1>Page Not Found: :PATH:</h1>
<p>Sorry, but the page requested is not available on this server.</p>
46 changes: 46 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#! /usr/bin/env node
// Quick-and-dirty web server using Node.js
var sys = require('sys');
var http = require('http');
var fs = require('fs');
var path = require('path');
var port = 8080;

http.createServer(function(request, response) {
var url = request.url;
if (url === '/')
url = '/index.html';

if (url === '/time') {
response.writeHeader(200, {
"Context-Type": "text/plain",
"Access-Control-Allow-Origin": "http://localhost/"});
response.write(new Date().toString());
response.end();
}

fs.readFile(path.join('.', url), function (err, data) {
if (err) {
if (err.code === 'ENOENT') {
fs.readFile('page404.html', function(err, data) {
if (err)
throw err;
response.writeHeader(404, {
"Content-Type": "text/html"});
response.write(data.toString()
.replace(/:PATH:/g, url));
response.end();
});
} else throw err;
} else {
// :TODO: determine content type --
// by file extension?
// by contents?
// a combination of both?
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(data);
response.end();
}
});
}).listen(port);
console.log('Server listening: http://localhost:' + port + '/');

0 comments on commit 415c918

Please sign in to comment.