Node JS – Services + Globals (Sails JS)

We can define our services inside the “api/services” folder. Each service defined here will be globally accessible by its file name (without extension).

module.exports = {
     myServiceMethod: function (args) {
          return ...;
     }
};

However this approach has some limitation: all the services have to stay on the same level (sub-folders are not supported). So is better to disable this behaviour and to directly go through the standard Node JS require() mechanism.

To disable it we can edit the “config/globals.js” file in this way:

module.exports.globals = {
     ...

     services: false
}

Then we can refer the service we need from any controller or other service in this way (please note that we are using the npm module “app-root-path” to get the root path):

var appRoot = require("app-root-path");
var myService = require(appRoot + "/api/services/myService");

module.exports = {
     ...
}

This is the standard way in Node JS to require a module given its path.


Having a service globally available

Since we disabled the automatic behaviour we now have to explicitly require every service we need. However it could be useful to have some service automatically available without needing to request it everywhere. To have this we can add them to the global object by editing the “config/bootstrap.js” file:

global.appRoot = require('app-root-path');
global.myUtilService = require(global.appRoot + "/api/services/utils/myUtilService");

module.exports.bootstrap = function(cb) {
     ...
};

In this way we can refer the service through global.myUtilService (or even just myUtilService)from everywhere.


Specifying the current path to Node JS (NODE_PATH)

To avoid using external modules like “app-root-path” we can launch Node JS with the information of the current path we want it to consider when we require for modules. In this way we can use relative paths with no problems.

In order to do this we can specify the path with an environment variable before starting the app (in any of the ways we can start it), here is an example:

NODE_PATH=. npm start

In order to have VS Code doing the same thing when we debug the application we can edit its launch configuration (under “.vscode/launch.json”) to add “NODE_PATH”: “.” to the “env” node of the “launch” configuration.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s