- We need to create an external file and use module.exports. We can emit module.
- Create a function named as firstName and lastName assign string values as shown below
Example 1
Create a new file
//When we use functions we have to use module module.exports={ firstName:function(){ return "My First is Prathap"; }, lastName:function(){ return "My lastName is Kudupu"; } };
- Specify the path of the JavaScript file to be referred in the file'
- Now we can directly use the function as shown below
Reference the file using require
console.log("Reference other file functions in node"); //Refer other javascript file. dependency management var greetings=require("./referencefile.js"); //call the function from the other Javascript file console.log(greetings.firstName()); console.log(greetings.lastName());
Output
- Run the JavaScript code in node
c:\Development\NodeProjects\vanilanode>node app Reference other file functions in node My First is Prathap My lastName is Kudupu
Example 2
In this example we are setting the values in the constructor//When we use functions as a con module.exports= function(){ this.firstName= "My First name is Prathap from class"; this.lastName= "My Last name is Prathap"; };
We need to create a new instance of the class. We can then use the properties
console.log("Reference other file functions in node"); //Export a class from other file var classGreetings=require("./classReference.js"); //Declare an instance of a class var greetClass=new classGreetings //call the function from the other Javascript file console.log(greetClass.firstName);
c:\Development\NodeProjects\vanilanode>node app Reference other file functions in node My First name is Prathap from class
No comments:
Post a Comment