The require and include modules

Introduction

In order not to write the same code twice, we often need an include mecanism.
Cendre proposes two manners to do so. One for functions libraries, and the other for context-aware inclusions.

Functions libraries inclusions

Node.js already has a mecanism for inclusions. For instance, create a library by creating a file called mylib.nodejs with this content :

exports.print_hello = function()
{
	return ('hello');
};

To use the print_hello() function, you have to write these lines in another .nodejs file located in the same folder.

var mylib = require('mylib.nodejs'); // Get the mylib.nodejs functions into the mylib namespace.
mylib.print_hello(); // Run the print_hello() function.

The Cendre require

I decided to extend the execution cache management to included libraries. So you can use libraries this way :

var r = require(c.m.require); // Get the require function into the r namespace.
var mylib = r.require('mylib.nodejs', c); // Get the mylib.nodejs functions into the mylib namespace.
mylib.print_hello(); // Run the print_hello() function.

NB : do not use the Cendre require with libraries installed via npm.

Context-aware inclusions

I also made a module to include .nodejs pages. You can pass arguments, and get the result into the including file.
The included file part.nodejs can look like this :

exports.run = function(c, p, end)
{
	end('parameter : ' + p.parameter);
};

To include it, you can write the following lines :

var i = require(c.m.include);
i.include('part.nodejs', c, {'parameter' : 'test'}, function(result)
{
	// Actions after include...
});

The variable passed to end() in part.nodejs can be retrived in the result parameter above.

Synchronising multiple context-aware inclusions

You will need to execute some code only after multiple inclusions have been made. Here's an example to do so :

var i = require(c.m.include);
var p = {'go' : 0, 'part1' : '', 'part2' : ''};

var ready = function()
{
	p.go += 1;

	if (p.go == 2)
	{
		// Actions to be made after inclusions.
	}
};

i.include('file1.nodejs', c, null, function(result)
{
	p.part1 = result;

	ready();
});

i.include('file2.nodejs', c, null, function(result)
{
	p.part2 = result;

	ready();
});