August, 2019
So we installed NodeJS on our machine.
Now we want to learn how to create our own module.
logger.js
:touch logger.js
// 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.
index.js
:touch index.js
// 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");
node index.js
[ERROR] This is an error message.
[SUCCESS] This is a success message.
type
? How can you solve this?Hi! I'm Michael 👋 I'm a Mentor & Educator & Senior Web Developer - I help you to reach your (career) goals.