p.campbell
p.campbell

Reputation: 100637

Including and grouping related functions in js files in Node Express

I've got a Node Express route file. It was getting large in its number of functions that weren't route related - code to hit Azure and other file name related functions.

I'm fairly sure I want to keep routing functions in the route file (here it's route/tally.js file, and functions for file name parsing in another file (i.e. fileName.js and tallyAzure.js).

  1. How can I tell my route.js file to include and refer all the functions that live inside another .js file.

    With the route js file, I've tried include("routes/tallyAzure.js");.

  2. Where's the most logical place in the solution to put these function files? I'm leaning towards a dir outside of the routes dir. Any naming conventions that I should be aware of?

enter image description here

Upvotes: 1

Views: 143

Answers (1)

Lee Jenkins
Lee Jenkins

Reputation: 2470

You'll want to use the exports variable. Here's an example from the documentation at: http://nodejs.org/api/modules.html

circle.js:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

app.js:

var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

Upvotes: 1

Related Questions