Two ways of writing modules
Using module.exports
const add = (n1, n2) => n1 + n2;
const sub = (n1, n2) => n1 - n2;
const mul = (n1, n2) => n1 * n2;
const div = (n1, n2) => n1 / n2;
module.exports = { add, sub, mul, div };
Using exports - when there are more than one functions/variables to be exported
exports.add = (n1, n2) => n1 + n2;
exports.sub = (n1, n2) => n1 - n2;
exports.mul = (n1, n2) => n1 * n2;
exports.div = (n1, n2) => n1 / n2;
How to use these modules?
Importing entire file
const test = require('./test');
console.log("add: ", test.add(2, 1));
console.log("sub: ", test.sub(2, 1));
console.log("mul: ", test.mul(2, 1));
console.log("div: ", test.div(2, 1));
Importing functions/variables that are to be used
const { add, sub } = require('./test');
console.log("add: ", add(2, 1));
console.log("sub: ", sub(2, 1));
That is it!
Comments
Post a Comment