runnable v3.0.0
Export a runnable function
Wraps a function so that it is called when run directly but returned when required in. This is especially useful for micro services and and SOA architectures, but can be used for many other things.
Usage
$ npm install runnableBasic usage:
// index.js
var runnable = require('runnable');
module.exports = runnable(function (opts) {
console.log(opts.foo);
}, [{
foo: 'bar'
}], module); // bar// bin/foo.js
var foo = require('../index.js');
foo({
foo: 'other bar'
}); // other barUsage with multiple runnable instances in one process is a little bit different due to the behavior
of node's module.parent implementation which sets the parent to the first module to import
the file, as opposed to the actual parent which required it in this time. So to work in this
kind of an enviornment you need to pass a final parameter to the runnable call.
var runnable = require('runnable');
module.exports = runnable(function foo () {
console.log('foo');
}, module);var runnable = require('runnable');
module.exports = runnable(function bar () {
console.log('bar');
}, module);var foo = require('../foo.js');
var bar = require('../bar.js');
foo(); // foo
bar(); // barUsage with Browserify
If you are using this module with browserify, it will not work by default. Browserify does
not implement module.parent or require.main. Luckily Browserify allows you to provide your
own require implementation via the prelude option. This module comes with an implementation
which implements the required fields. Hopefully this will get added so Browserify once I make
the case. In the mean time you can do this:
var b = browserify('index.js', {
prelude: require('runnable/browserify-prelude')
}).bundle();API
runnable(fnc <Function>[,defaults <Array>[, module <Object>]]);fnc: The runnable functiondefaults: Defaults that will be passed to the function when called directlymodule: The module the function is declared in, literallymodulefrom the commonjs file
Usage in micro-services/SOA
This is an example of how we use this pattern to give production configuration to apps in our SOA setup. In development we just run node index.js, and in prod we run ./bin/server which loads production configuration and registers with our service discovery.
// index.js
var app = require('express')();
var runnable = require('runnable');
module.exports = runnable(function (opts) {
var server = app.listen(opts.port, function () {
console.log('Listening on ' + server.addresS().port);
});
}, [{
port: 4000
}], module);// bin/server
var app = require('../');
app({
port: null // run on a ephemeral port in production
});