Guides & Examples
Three small worked examples, copied and trimmed from the original README.
Example 1 — a logging plugin
The “Hello world” of asimov.js: a plugin that registers one initializer that logs a message.
asimov-log-message/ lib/ init/ logMessage.js index.js package.jsonmodule.exports = function initializer (next) { console.log('Hello world'); next();};var asimov = require('asimov');var logMessage = require('./lib/init/logMessage');
module.exports = function plugin () { asimov.init(logMessage);};
module.exports.start = function bootstrap () { asimov.use(module.exports).start();};
module.parent || module.exports.start();Run it:
$ asimov> Hello worldExample 2 — a custom CLI command
Add a loc command that counts lines of JavaScript code in lib/. Any project that installs this plugin gets asimov loc for free.
asimov-loc/ lib/ commands/ loc.js index.js package.jsonvar asimov = require('../../index');
function countLinesInPath (path) { // walk path recursively, sum lines in every .js file}
module.exports = function () { var path = process.cwd() + '/lib'; var started = new Date(); var count = countLinesInPath(path);
asimov.logger.since('loc', 'Counted ' + count + ' lines in ' + path, started);};The CLI auto-discovers any file under lib/commands/, in your project and in each node_modules/* dependency. Project commands win over dependency commands of the same name.
Example 3 — a render sequence
This is how asimov-pages implements rendering. The sequence is named, then any plugin can push processors onto it.
asimov.addSequence('render');
asimov.render(function (page, next) { page.html = renderMarkdown(page.body); next();});
asimov.render(function (page, next) { page.html = minify(page.html); next();});
asimov.runSequence('render', somePage) .done(function (page) { writeFileSync(page.path, page.html); }) .fail(function (err) { console.error(err); });The key idea: processors don’t know about each other. Each one mutates the page and calls next(). New behaviours are added by new processors, not by editing existing ones.