Create your own module in Nodejs
Exports
Direct exports function declaration
Create new file mydate.js and write the following code
exports.myDateTime = function () {
return Date();
};
Export after function declaration
Declare function and write the definition. Then exports.
function getPlus(a, b) {
return a + b;
}function getMultiply(a, b) {
return a*b;
}exports.getPlus = getPlus;exports.getMultiply = getMultiply;
Or, without using function, write the following codes
const getName = () => {
return ‘Skywalker’;
}const getOrigin = () => {
return ‘Tatooine’;
}exports.getName = getName;exports.getOrigin = getOrigin;
Module.exports
function getPlus(a, b) {
return a + b;
}function getMultiply(a, b) {
return a*b;
}module.exports = {getPlus,getMultiply}
Importing the Modules
Use require — assign the result to a variable. This can then be used to invoke any methods the module exposes
var dt = require(‘./myfirstmodule’)
..console.log(‘Current date and time : ‘ + dt.myDateTime());.