Skip to content

Instantly share code, notes, and snippets.

@codemoran
Last active December 11, 2015 21:28
Show Gist options
  • Save codemoran/4662537 to your computer and use it in GitHub Desktop.
Save codemoran/4662537 to your computer and use it in GitHub Desktop.
A Simple node.js HTTP webserver with some file IO and graphdat integration
require('graphdat').config({suppress:{context_pop_automatic:true}}); // require the graphdat module first, always!
var fs = require("fs"); // require the Filesystem module so we can read and write files
var http = require("http"); // require the HTTP module
//
// ### function createServer (requestCallback)
// #### @requestCallback {function} function is called on every request made.
//
http.createServer(function (request, response) {
request.on('end', function () {
// Check if user requests / (so we don't have to worry about favicon.ico)
if (request.url == '/') {
// tell graphdat to instrument this
request.graphdat.begin('start reading a file');
// Read a file.
fs.readFile('test.txt', 'utf-8', function (error, data) {
// tell graphdat the event is over
request.graphdat.end('start reading a file');
// start another trace
request.graphdat.begin('response.write');
// Write headers.
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Write out the text file to the user
// Graphdat is smart enough to know the trace is still open
// and will automatically add in the 'end' on its own. Thats
// why we added that extra config option in the require
response.end(data);
});
} else {
request.graphdat.begin('response.write 404');
// Indicate that requested file was not found.
response.writeHead(404);
// And end request without sending any data.
// Graphdat is smart enough to end the trace on its own
response.end();
}
});
// Listen on the 8080 port.
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment