node-cgi

use node as CGI module

licenseMITgithublrsjng/node-cginpmnode-cgi
0.3.0

Use Node.js like PHP as a CGI-module in web servers.

Getting started

Install node-cgi globally with npm:

> npm install -g node-cgi

To use it with an Apache httpd web server create a link to bin/node-cgi inside your cgi-bin directory. Then add the following lines to your config or .htaccess file:

Action       "node-script"  "/cgi-bin/node-cgi"
AddHandler   "node-script"  ".nd"

assuming that /cgi-bin/ is the path to your CGI directory. This will run all files *.nd through the Node.js CGI module.

A example file hello.nd is a plain JavaScript file and could look like:

header('Content-Type', 'text/plain');

writeLine('Hello!');
writeLine(dirname);
writeLine(filename);

Another example file hello.html.nd is a HTML file and could look like:

<?js
    header('test', true);

    var _ = require('underscore');
    var s = '';

    _.each('a b c'.split(' '), function (part) {

        s += part + part;
    });
?>

<!DOCTYPE html>
<html>
    <body>
        <h1>hello</h1>
        <h2><?js write(s) ?></h2>
        <h2><? write(s) ?></h2>
        <h2><?= s ?></h2>
    </body>
</html>

Globals

The following globals are defined inside the context of a file:

// the file and directoy name of the current file
filename: String
dirname: String
// requires a module
// arg might be an module name, an absolute or relative path
require(arg: String): anything
// processes another 'node-cgi' file
processFile(filename: String): HttpResponse
// sets a HTTP header field
header(key: String, value: String): undefined
// write s to the HTTP content, optionally add new-line-characters (CRLF)
write(s: String): undefined
writeLine(s: String): undefined

HTML files

Inject your JavaScript code into HTML files

<?js /* ... some JavaScript code here ... */ ?>
<?js
    /* ... multiline code is fine too ... */
?>
<?= i ?>        // same as <?js write(i); ?>
<?= "hello" ?>  // same as <?js write("hello"); ?>