Alvaro
Alvaro

Reputation: 41595

Where to place common functions in express.js?

I am wondering where common functions should be placed in the express structure to be shared between different routes.

Is there any "best practice" for it? Nothing is mention in the documentation about it.

Upvotes: 5

Views: 3233

Answers (1)

Kevin Reilly
Kevin Reilly

Reputation: 6242

They should be placed in an include that you require from each route.

common.js

function Common(){}

Common.prototype.method1 = function(){}
Common.prototype.method2 = function(){}

module.exports = new Common();

route.js

var common = require('./common');
common.method1();
common.method2();

Upvotes: 12

Related Questions