Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
puffnfresh committed Apr 26, 2010
0 parents commit f863bc2
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 0 deletions.
73 changes: 73 additions & 0 deletions cgi.js
@@ -0,0 +1,73 @@
var sys = require('sys'),
http = require('http');

var Request = function() {
this.method = process.env['REQUEST_METHOD'];
this.headers = {
'host': process.env['HTTP_HOST'],
'user-agent': process.env['HTTP_USER_AGENT']
};
this.url = process.env['REQUEST_URI'];
};

var Response = function() {
var body = false;

this.writeHead = function() {
var status = arguments[0];
var reason = arguments[1];
var headers = arguments[2];

if(typeof reason != 'string') {
headers = reason;
reason = http.STATUS_CODES[arguments[0]] || 'unknown';
}

sys.puts('Status: ' + status + ' ' + reason);

var field, value;
var keys = Object.keys(headers);
var isArray = (headers instanceof Array);
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
if (isArray) {
field = headers[key][0];
value = headers[key][1];
} else {
field = key;
value = headers[key];
}

sys.puts(field + ": " + value);
}
};

this.write = function(message) {
if(!body) {
body = true;
sys.puts("");
}

if(message) sys.print(message);
};

this.flush = function() {
};

this.end = function() {
this.write.apply(this, arguments);
};
};

var Server = function(listener, options) {
var request = new Request();
var response = new Response();

this.listen = function() {
listener(request, response);
};
};

exports.createServer = function(listener, options) {
return new Server(listener, options);
};
31 changes: 31 additions & 0 deletions readme.md
@@ -0,0 +1,31 @@
# node-cgi

This library is a CGI adaptor for node.js

It is designed to help people run node.js websites off of a shared server (CGI is so old it's available almost *everywhere*).

## Usage

You'll have to create a `.htaccess` file that rewrites everything to a CGI script:

Options +ExecCGI
AddHandler cgi-script cgi

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) server.cgi

Copy `cgi.js` to the same directory and make the actual CGI script (`server.cgi` in this example):

#!/usr/bin/env node

var cgi = require('./cgi');

var server = cgi.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('This is CGI!');
response.end();
});
server.listen();

As you can see, using the `cgi` library is very similar to the `http` library in node.js

0 comments on commit f863bc2

Please sign in to comment.