DEV Community

miku86
miku86

Posted on • Edited on

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
Enter fullscreen mode Exit fullscreen mode
  • 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
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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');
Enter fullscreen mode Exit fullscreen mode

Run it from the terminal

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

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?

Top comments (0)