node package manager


service locator for node.js apps


service locator for node js

Allow to load instanse of service with injected dependency of other service. Service dependencies are described in declarative way. Locator is a singletone so you can register services ones and then use it everywhere in your app


npm install node-service-locator


Simple Services

Lets assume that we have a folder 'Services' in project and and file Logger with logger service in it.

// Services/Logger.js 
exports.log = function (msg) {

Service description example

// services.js file 
module.exports = {
    "logger": {
        "path": "Services/Logger"

Usage Example

var serviceList = require('./services');
var basePath = __dirname;
var locator = require('node-service-locator');
locator.init(serviceList, basePath);
//load simple object 
var logger = locator.get('logger');

Servise as a constructor function

// Services/ClassLogger.js 
var ClassLogger = function (errorLevel) {
    this.level = errorLevel || "debug";
ClassLogger.prototype.log = function(message) {
    console.log(this.level, message);
module.exports = ClassLogger;

In order to return from locator an instance of this service you should add instantiate and parameters keys to service description

"warningLogger": {
    "path": "Services/ClassLogger",
    "instantiate": true,
    "params": ["warning"]

And than in you app:

var warningLogger = locator.get('warningLogger');

Also you have possibility to pass one service as a parameter to anather to do this add '@' to service name in the params field

"ClassWithWarningLogger": {
    "path": "Services/ClassWithWarningLogger",
    "instantiate": true,
    "params": ["foo", "@warningLogger", 23]

Also you can register some services on th fly

locator.register('foo', {name: 'foo'});
// => foo 

Invoke some function with services as parameters

locator.register('foo', {name: 'foo'});
locator.invoke('foo', 'logger', function (foo, logger) {
// => foo 



More examples in example folder