Node Modules

Question Click to View Answer

Create a ~/Desktop/fun_m/a.js file with the following contents.

function a() {
  return "This is A";
}

module.exports.a = a;

Create a ~/Desktop/main.js file that runs the a() method and prints the contents to the log.

Contents of the ~/Desktop/main.js file:

const path = `${process.env.HOME}/Desktop/fun_m/a.js`;
const ourNamespace = require(path);

console.log(ourNamespace.a());

The require method is used to import the a() function. The function is not imported in the global namespace - it's bound to the something constant.

The main.js file can be run with this command:

node ~/Desktop/main.js

Create a ~/Desktop/fun_m/b.js file with the following contents.

module.exports = {
  fullName: function(first, last) {
    return `${first} ${last}`;
  }
}

Update the ~/Desktop/main.js file to use the fullName function to print "pam anderson" to the log.

Contents of the ~/Desktop/main.js file:

const path = `${process.env.HOME}/Desktop/fun_m/b.js`;
const moe = require(path);

console.log(moe.fullName("pam", "anderson"));

The moe object is created and the fullName function is bound to the moe object. The Node require method cannot be used to import modules into the global namespace. Imports must be bound to objects.

Create a ~/Desktop/fun_m/c.js file with the following contents.

class Calculator {
  add(a, b) {
    return(a + b);
  }
}

module.exports = Calculator;

Update the ~/Desktop/main.js file to use the add() method to sum 3 and 4.

Contents of the ~/Desktop/main.js file:

const path = `${process.env.HOME}/Desktop/fun_m/c.js`;
const Bort = require(path);

const myBort = new Bort();
console.log(myBort.add(3, 4));

Use the os core module to print the hostname to the console.

const os = require('os');
console.log(os.hostname());

The require keyword can also be used to load core modules. Node has several built-in core modules (e.g. timers, file system, https).

Create a ~/Desktop/fun_m/package.json file with the following contents.

{
  "name" : "myModule",
  "main" : "./stimpy.js"
}

Create a ~/Desktop/fun_m/stimpy.js file with the following contents:

module.exports = {
  speak: function() {
    return "happy, happy, joy, joy";
  }
};

Update the ~/Desktop/main.js file to use the speak function to print "happy, happy, joy, joy" to the log.

Contents of the ~/Desktop/main.js file:

const path = `${process.env.HOME}/Desktop/fun_m`;
const fun = require(path);

console.log(fun.speak());

The path variable points to a directory in this example. Node looks in the package.json file which specifies the code entry point as the stimpy.js file with the main property.