Why not use the javascript VM as preprocessor? Node is about putting more javascript into javascript anyway.
Every line starting with '#' is coded in the preprocessor context, every line that isn't, is for the result.
I wrote it in a way, so line numbers are ought to be preserved unless an include( ) happens, in that case line numbers go a little amiss.
example input.js:
For example:
preprocessor.js:
-----------------------------
var fs = require( 'fs' );
var vm = require( 'vm' );
var file = fs.readFileSync( 'input.js' ).toString( );
var lines = file.split('\n');
var skipped = '';
var code = [ ];
var result;
for( var ln in lines )
{
var line = lines[ ln ];
if( line[ 0 ] === '#' )
{
lines[ ln ] = line.substr( 1 );
skipped += '\\n';
}
else
{
lines[ ln ] =
'code.push("'
+ skipped
+ line.replace( /\"/g, '\\"' ).replace( /"/g, '\\"' )
+ '");';
skipped = '';
}
}
lines.push( 'code; ');
result =
vm.runInNewContext(
lines.join( '\n' ),
{
code : code,
require : require,
include :
function( filename )
{
code.push( fs.readFileSync( filename ) );
}
}
)
.join( '\n' );
console.log( result );
-------------------
Do with result what you want, like using it in the http server module, cache it, etc. you might wrap some async code to replace readFileSync() with async alternatives in the flow control of your choice.
------------------------
#var test = require( './test' );
#if( test ) {
console.log( '"hello"' );
#}
console.log( 'world' );
#include( 'include-me.js' );
-----------------------
example test.js :
------------------------
// just contains a yes/no switch
module.exports = true || false;
----------------------------
Handing the preprocessors own require function to the to be preprocessed file might be a little naive and have quirky effects if they use the same files, I just suppose its trusted code anyway, but for a starter it works. Might be replaced with a custom require if so desired.
One can also directly alter the 'code' array in preprocessor context to add custom stuff.