NodeJS: How To Create Your Own Module

Intro

So we installed NodeJS on our machine.

Now we want to learn how to create our own module.

Write a simple script

  • Open your terminal
  • Create a file named logger.js:
touch logger.js
  • Add this JavaScript code into it:
// the function should get a message type and a message
function logger(type, message) {
  let format;

  // different message for different message type
  switch (type) {
    case "error":
      format = `[ERROR] ${message}`;
      break;
    case "success":
      format = `[SUCCESS] ${message}`;
      break;
    default:
      format = `${message}`;
      break;
  }

  console.log(format);
}

// export the function using object property shorthand syntax
// to rename, use "newName: logger"
module.exports = {
  logger,
};

Note: For the sake of simplicity, this example is very lightweight, has no error/edge-case handling (e.g. no type), no separate file for the message types, no colors etc.


Write a second simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
  • Add this JavaScript code into it:
// import the exported logger property
const { logger } = require("./logger.js");

// use the function
logger("error", "This is an error message.");
logger("success", "This is a success message");

Run it from the terminal

  • Run it:
node index.js
  • Result:
[ERROR] This is an error message.
[SUCCESS] This is a success message.

Next Steps

  • Q: What happens, when you forget to add a type? How can you solve this?
  • Q: How can you improve this example by separating the message types into a constant?
  • Q: How can you improve this example by using an object as parameter instead of two strings?
  • Q: Do you need some additional error handling? (=> Docs)

Further Reading


Questions

  • What is your favorite self-written module, that improves your developer life?