Skip to content

Instantly share code, notes, and snippets.

@lucasjones
Last active January 29, 2017 05:49
Show Gist options
  • Save lucasjones/5319093 to your computer and use it in GitHub Desktop.
Save lucasjones/5319093 to your computer and use it in GitHub Desktop.
Simple node.js static and dynamic file express server
/***********************************
*Simple node.js static and dynamic file express server
*Author: Lucas Jones
***********************************/
//Load node.js modules
var express = require('express'); //Require the Express Module
//Runs every time a request is recieved
function logger(req, res, next) {
console.log('Request from: ' + req.ip + ' For: ' + req.path); //Log the request to the console
next(); //Run the next handler (IMPORTANT, otherwise your page won't be served)
}
var port = 8000;
var app = express(); //Initialize the app
//Configure the settings of the app
app.configure(function () {
app.use(express.bodyParser()); //Parses the POST data for each request
app.use(express.cookieParser()); //Parses the Cookie data for each request
app.use(logger); //Tells the app to send all requests through the 'logger' function
app.use(app.router); //Tells the app to use the router
app.use(express.static('./public_html/')); //Tells the app to serve static files from ./public_html/
});
//Example of a dynamic get handler
app.get('/dynamicfile.txt', function(req, res) {
res.setHeader('Content-Type', 'text/plain'); //Tell the client you are sending plain text
res.end(req.cookies);
});
//Example of a dynamic post handler
app.post('/dynamicfile.txt', function(req, res) {
res.setHeader('Content-Type', 'text/plain'); //Tell the client you are sending plain text
res.write('Posted data to server: '); //Send data to the client
res.end(req.body); //Send the post data to the client and end the request
});
app.listen(port); //Listen on the specified port
console.log('Listening on port ' + port); //Write to the console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment