Created
October 21, 2012 18:12
-
-
Save cawoodm/3927946 to your computer and use it in GitHub Desktop.
NodeSP (Node Server Pages) is a proof of concept on using Node.js as a web server serving dynamic content generated from .js scripts akin to PHP or other CGI scripts.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
url = require('url'), | |
vm = require('vm'), | |
fs = require('fs'); | |
// Process request and send response to client | |
exports.run = function(request, response) { | |
var res = this.process(request); | |
response.statusCode = res.statusCode||200; | |
response.setHeader("Content-Type", res.contentType||"text/html"); | |
response.end(res.body); | |
} | |
// Process request and return response as object | |
exports.process = function(request) { | |
request.url = url.parse(request.url, true); | |
var filename = '.'+request.url.pathname; | |
// Load .js script | |
if (!fs.existsSync(filename)) return {statusCode: 404, body: 'Script not found!'}; | |
var jsCode = fs.readFileSync(filename); | |
// Prepare context with request and response | |
var context = {request: request, response: {}, console: console}; | |
try { | |
// Run script | |
vm.runInNewContext(jsCode, context); | |
} catch(e) { | |
context.response.statusCode = 500; | |
context.response.body = 'NodeSP error processing script : ' + e.message + '<pre>' | |
+ e.stack + '</pre>'; | |
} | |
// Return response | |
return context.response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put the above nodesp.js in your node_modules folder and then run the following nodespserver.js:
Finally create your test.js:
If you then call localhost:8111/test.js you should see "Hello World!" printed in large, friendly letters.