Skip to content

Instantly share code, notes, and snippets.

@cawoodm
Created October 21, 2012 18:12
Show Gist options
  • Save cawoodm/3927946 to your computer and use it in GitHub Desktop.
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.
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;
}
@cawoodm
Copy link
Author

cawoodm commented Oct 21, 2012

Put the above nodesp.js in your node_modules folder and then run the following nodespserver.js:

var http = require('http'),
    nsp  = require('nodesp');

http.createServer(function (req, res) {
    nsp.run(req, res);
}).listen('8111');

Finally create your test.js:

response.body = '<h1>Hello World!</h1>';

If you then call localhost:8111/test.js you should see "Hello World!" printed in large, friendly letters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment