modules

October 22, 2022

modules

Stability: 2 - Stable

CloudControl has a simple module loading system. In CloudControl, files and modules are one-to-one (each file is treated as a separate module).

For example, suppose there is a file named foo.js.

var circle = require('circle.js');
console.log("The area of a circle with radius 4 is %d", circle.area(4));

In the first line, foo.js loads the circle.js module in the same directory.

The contents of the circle.js file are

const PI = Math;

var circle = {};

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

circle.circleference = (r) => 2 * PI * r;

module.exports = circle;

The circle.js module exports two functions, area() and circumference(). Functions and objects can be added to the root of the module by specifying additional properties on special exports objects.

Local variables within the module are private. In this example, the variable PI is private to circle.js and does not affect the variable environment of the script that loads it.

The module.exports property can be given a new value (e.g. a function or an object).

As follows, bar.js will use the square module, and square exports a constructor.

const square = require('square.js');
const mySquare = square(2);
console.log("The area of the square is %d", mySquare.area());
The square module is defined in square.js.

// Assigning to `exports` does not modify the module, you must use `module.exports`
module.exports = function(width) {
  return {
    area: () => width ** 2
  };
};
Last update:
Contributors: Bruce