console
.
log
(
amanda_calculate
(
1
,
2
,
5
));
// logs 31
console
.
log
(
tyler_calculate
(
2
));
// logs 33.510321638291124
Note that the names we chose (
amanda_calculate
and
tyler_calculate
) are totally
arbitrary; they are just variables. The value they’re receiving is the result of Node pro‐
cessing the
require
function.
The mathematically inclined reader may have already recognized these two calcula‐
tions: Amanda is providing the sum of the geometric series
a + ax + ax
2
+ . . . + ax
n − 1
, and Tyler is providing the volume of a sphere of radius r.
Now that we know this, we can shake our heads at Amanda and Tyler’s poor naming
practices, and choose appropriate names in app.js:
const
geometricSum
=
require
(
'./amanda.js'
);
const
sphereVolume
=
require
(
'./tyler.js'
);
console
.
log
(
geometricSum
(
1
,
2
,
5
));
// logs 31
console
.
log
(
sphereVolume
(
2
));
// logs 33.510321638291124
Modules can export a value of any type (even a primitive, though there’s little reason
for that). Very commonly, you want your module to contain not just one function,
but many, in which case you could export an object with function properties. Imagine
that Amanda is an algebraist who is providing us many useful algebraic functions in
addition to a geometric sum:
module
.
exports
=
{
geometricSum
(
a
,
x
,
n
) {
if
(
x
===
1
)
return
a
*
n
;
return
a
*
(
1
-
Math
.
pow
(
x
,
n
))
/
(
1
-
x
);
},
arithmeticSum
(
n
) {
return
(
n
+
1
)
*
n
/
2
;
},
quadraticFormula
(
a
,
b
,
c
) {
const
D
=
Math
.
sqrt
(
b
*
b
-
4
*
a
*
c
);
return
[(
-
b
+
D
)
/
(
2
*
a
), (
-
b
-
D
)
/
(
2
*
a
)];
},
};
This results in a more traditional approach to namespacing—we name what’s
returned, but what’s returned (an object) contains its own names:
const
amanda
=
require
(
'./amanda.js'
);
console
.
log
(
amanda
.
geometricSum
(
1
,
2
,
5
));
// logs 31
console
.
log
(
amanda
.
quadraticFormula
(
1
,
2
,
-
15
));
// logs [ 3, -5 ]
There’s no magic here: the module is simply exporting an ordinary object with func‐
tion properties (don’t let the abbreviated ES6 syntax confuse you; they’re just func‐
tions). This paradigm is so common that there’s a shorthand syntax for it, using a
special variable simply called
exports
. We can rewrite Amanda’s exports in a more
compact (but equivalent) way:
Modules | 283