Export a Class from a Module in Node.js 6
learn how to export classes in ECMAScript 6
6. To keep it simple, we have organized it into 2 sections. In the first section we create a class with some functions and we add the statement to export the class. In the second section, we simply write the code to use that class.
Let's Get Started with Code.
Step-1 Create a Class File & Export it
Create a file with the name Ganit.js and add the following code to it.
this.x = x;
this.y = y;
return this.x + this.y;
return this.x - this.y;
return this.x * this.y;
return this.x / this.y
return this.x % this.y
module.exports = Ganit
Note the ECMAScript6 features being utilized while writing the above code. It's tested to work fine in Node v6.4.0
Step-2 Import the file and use it!
Create another file Test.js in the same directory as above and add following code to it.
var Ganit = require('./Ganit.js');
var calc = new Ganit(3,4);
console.log("addition of operands is: " + calc.add());
console.log("subtraction of operands is: " + calc.subtract());
console.log("multiplication of operands is: " + calc.multiply());
console.log("quotient on dividing operands is: " + calc.divide());
console.log("remainder on dividing operands is: " + calc.remainder());
On executing the file Test.js . We get the following output.
addition of operands is: 7
subtraction of operands is: -1
multiplication of operands is: 12
quotient on dividing operands is: 0.75
remainder on dividing operands is: 3
We learned how to use the ECMAScript6 syntax to write classes in nodejs6 and how to export and import those classes.