[[oktatas:web:nodejs|< Node.js]]
====== Node.js modul ======
* **Szerző:** Sallai András
* Copyright (c) 2021, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== Modulkészítés =====
==== Érték exportálása ====
module.exports = 3.14
const pi = require('./pi.js');
console.log(pi)
==== Függvények objektumon keresztül ====
Két függvényt a triangle objektumon keresztül érünk el:
module.exports = {
calcPerimeter: function (sidea, sideb, sidec) {
return sidea + sideb + sidec;
},
calcArea: function (base, height) {
return base*height/2;
}
}
const triangle = require('./triangle.js');
console.log(triangle.calcPerimeter(30, 35, 40));
console.log(triangle.calcArea(30, 35));
A triangle objektum. De kinyerhetem belőle a két függvényt:
const triangle = require('./triangle.js');
const calcPerimeter = triangle.calcPerimeter;
const calcArea = triangle.calcArea;
console.log(triangle.calcPerimeter(30, 35, 40));
console.log(triangle.calcArea(30, 35));
console.log(typeof(calcArea));
==== Függvény exportálása ====
module.exports = function(base, height) {
return base*height;
}
const rectangleArea = require('./rectangleArea.js');
console.log(rectangleArea(30, 35));
==== Objektum exportálása ====
module.exports = [
{ name: 'Nagy János', city: 'Hatvan' },
{ name: 'Kis Irén', city: 'Szolnok'}
];
const employees = require('./employees.js');
console.log(employees[0].name);
===== Helyi változók =====
let maxSize = 100;
module.exports = {
calcPerimeter: function (sidea, sideb, sidec) {
if ( sidea < maxSize &&
sideb < maxSize &&
sidec < maxSize)
return sidea + sideb + sidec;
else
console.log("Error! Side is too large!");
},
calcArea: function (base, height) {
if (base < maxSize && height < maxSize)
return base*height/2;
else
console.log("Error! Side is too large!");
}
}
===== Osztály =====
module.exports = class Employee {
constructor(name, city) {
this.name = name || 'Névtelen';
this.city = city || 'Ismeretlen';
}
}
const Employee = require('./employee.js');
const janos = new Employee('Nagy János', 'Szolnok');
console.log(janos.name);
console.log(typeof(Employee));
console.log(typeof(janos));
Az Employee függvényként jelenik meg, de a janos már objektumoként.
===== Források =====
* https://www.hacksparrow.com/nodejs/writing-modules.html (2021)
* https://initialcommit.com/blog/nodejs-module (2021)
* https://docs.npmjs.com/creating-node-js-modules (2021)
* https://www.digitalocean.com/community/tutorials/how-to-create-a-node-js-module (2021)