node-cgi
Node as CGI-module
Use Node.js like PHP as a CGI-module in web servers. Proof of concept, don't use in production.
Getting started
Install node-cgi locally or globally with npm. To use it with an Apache httpd web server create a link to bin/node-cgi
inside your cgi-bin
directory and add the following lines to your httpd 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.
An example file hello.nd
could look like:
<?js
header('Content-Type', 'text/plain');
write('Hello!');
?>
Another example file hello.html.nd
is a HTML file and could look like:
<?js
header('test', true);
const fac = n => n < 2 ? 1 : n * fac(n - 1);
?>
<!DOCTYPE html>
<html>
<body>
<h1>hello</h1>
<h2><?js write(fac(5)) ?></h2>
<h2><? write(fac(7)) ?></h2>
<h2><?= fac(10) ?></h2>
</body>
</html>
Globals
The following globals are defined inside the context of a file:
// environment object, access to the CGI variables
env: object
// set a HTTP header field, "Content-Type" is preset to "text/html"
header(key: String, value: String): undefined
// write s to the HTTP content
write(s: String): undefined
// requires a module, arg might be an module name, an absolute or relative path
require(arg: String): any
// self-reference to the global space
global: object
Mappings
After the initial evaluation of the page content additional renderers are used based on the file extension: *.pug.nd
, *.md.nd
.
Inject your JavaScript code into files.
<?js /* ... some JavaScript code here ... */ ?>
<?js
/* ... multiline code is fine too ... */
?>
<?= i ?> // same as <?js write(i); ?>
<?= 'hello' ?> // same as <?js write('hello'); ?>