Advertisement
karlakmkj

Node.js - module.exports, require()

Oct 7th, 2021
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* shape-area.js */
  2. const PI = Math.PI;
  3.  
  4. // declare and export two functions
  5. function circleArea(r) {
  6.   return PI * r * r;
  7. }
  8. function squareArea(side) {
  9.   return side * side;
  10. }
  11.  
  12. // then add them as properties to the built-in module.exports object, to make these functions available to other files
  13. module.exports.circleArea = circleArea;
  14. module.exports.squareArea = squareArea;
  15.  
  16. console.log(circleArea(5));
  17. console.log(squareArea(5));
  18.  
  19. --------------------------------------------------------------------------------------------------------------
  20. /* app.js */
  21.  
  22. const radius = 5;
  23. const sideLength = 10;
  24.  
  25. // Option 1: import the entire shape-area.js module here (file path, file name & code from above)
  26. const areaFunctions = require('./shape-area.js');
  27.  
  28. // Option 2: import circleArea and squareArea with object destructuring - to extract only the needed functions.
  29. //const { circleArea, squareArea } = require("./shape-area.js")
  30.  
  31. // use the imported .circleArea() and .squareArea() methods here
  32. const areaOfCircle = areaFunctions.circleArea(radius);   //then can use the method imported from the file here
  33. const areaOfSquare =  areaFunctions.squareArea(sideLength);
  34.  
  35. console.log(areaOfCircle);
  36. console.log(areaOfSquare);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement