Skip to content
bobby_dreamer

Calling NodeJS Functions from external files

nodejs1 min read

When you are modularizing your code in NodeJS, functions are the easiest one to move another file. Problem is there are multiple ways, patterns when externalizing functions there is nothing like a best practise. You will just have to pick a pattern that fits your need and go along with it.

Here are few patterns i have come across and i haven't named the approaches.

index.js
1const express = require('express');
2const app = express();
3
4
5// # Method 1
6// module.exports in this case is exporting an object literal and the object has three functions and one variable.
7// forces us to use a namespace
8const foo = require("./local_functions/foo");
9
10// # Method 2
11require('./local_functions/bar')();
12
13// # Method 3
14const { add, sub, multiply, pi } = require('./local_functions/baz');
15
16// # Method 4
17const { divide } = require('./local_functions/qux');
18
19/************************************************/
20// Middleware - Simple request time logger
21app.use((req, res, next) => {
22 console.log("A new request received at " + Date.now());
23 next();
24});
25
26/************************************************/
27// Routes
28
29app.get('/', (req, res) => res.send('Hello World!'));
30
31
32app.get('/add/:x/:y', (req, res) => {
33 let x = req.params.x
34 let y = req.params.y
35 console.log(foo)
36 console.log(typeof foo.addNumbers)
37 console.log(typeof foo.pi)
38 let result = foo.addNumbers(x,y)
39 res.send(`Foo Add: ${x} + ${y} = ${result}`);
40});
41
42app.get('/sub/:x/:y', (req, res) => {
43 let x = req.params.x
44 let y = req.params.y
45 console.log(typeof subtracting)
46 console.log(typeof pii)
47 let result = subtracting(x,y)
48 res.send(`Bar Sub: ${x} - ${y} = ${result}`);
49});
50
51app.get('/multiply/:x/:y', (req, res) => {
52 let x = req.params.x
53 let y = req.params.y
54 console.log(typeof multiply)
55 console.log(typeof pi)
56 let result = multiply(x,y)
57 res.send(`Baz Multiply: ${x} * ${y} = ${result}`);
58});
59
60app.get('/divide/:x/:y', (req, res) => {
61 let x = req.params.x
62 let y = req.params.y
63 console.log(typeof divide)
64 console.log(typeof pi)
65 let result = divide(x,y)
66 res.send(`Qux divide: ${x} * ${y} = ${result}`);
67});
68
69
70/************************************************/
71// Final Invalid Route
72app.get('*', (req, res) => {
73 res.send('404! This is an invalid URL.');
74});
75
76/************************************************/
77// Listener
78app.listen(3000, () => console.log('Example app listening on port 3000!'));

Method 1 - foo

./local_functions/foo.js
1function add(x, y) {
2 inputs(x,y)
3 return x + y;
4}
5
6function subtract(x, y) {
7 inputs(x,y)
8 return x - y;
9}
10
11function multiply(x, y) {
12 inputs(x,y)
13 return x * y;
14}
15
16function inputs(x, y) {
17 console.log(`Inputs: x=${x}; y=${y}`)
18}
19
20const pi = 3.14159;
21
22module.exports = { addNumbers:add, subtract, multiply, pi };

Method 2 - bar

./local_functions/bar.js
1// To require it as a function, it needs to be exported as a function
2module.exports = function() {
3 this.adding = function(x, y) {
4 display(x,y)
5 return x + y
6 };
7 this.subtracting = function(x, y) {
8 display(x,y)
9 return x - y
10 };
11 this.multiplying = function(x, y) {
12 display(x,y)
13 return x * y
14 };
15 this.display = function (x, y) {
16 console.log(`Inputs: x=${x}; y=${y}`)
17 };
18 this.pii = 3.14159
19}

Method 3 - baz

./local_functions/baz.js
1module.exports.add = function (x, y) {
2 return x + y;
3 }
4
5module.exports.subtract = function (x, y) {
6 return x - y;
7 }
8
9module.exports.multiply = function (x, y) {
10 return x * y;
11 }
12
13module.exports.inputs = function (x, y) {
14 console.log(`Inputs: x=${x}; y=${y}`)
15 }
16
17module.exports.pi = 3.14159

Method 4 - qux

./local_functions/qux.js
1module.exports = {
2 adding: function (x, y) {
3 display(x,y)
4 return x + y;
5 },
6
7 subtracting: function (x, y) {
8 display(x,y)
9 return x - y;
10 },
11
12 divide: function (x, y) {
13 display(x,y)
14 return x / y;
15 },
16
17 display: function (x, y) {
18 console.log(`Inputs: x=${x}; y=${y}`)
19 },
20
21 pii: 3.14159,
22 };

I sort of seem to like method 3 - baz approach.


Thanks for reading