Saturday 8 August 2015

How to create a simple Test Module in Node JS

In this tutorial I am going to describe on how to create a simple test  app using node js.

Step1: Download the latest version of nodejs from https://nodejs.org/download/
 Once the installer is downloaded install it on your system.
 After the installation, you can check the version of nodejs by typing the below command
node -v 

Step 2: Creating a sample web app  using node js
 Open the command prompt, and go to your working directory
   Here I am using D:\\code\test folder
npm init command can be used to create your package.json for your testapp as shown below.
It will prompt you for values for the package.json fields. The two required fields are name and version. You'll also need to have a value for entry point. You can use the default, index.js.



Step 3:  Now we can go-ahead and create our new index.js as specified while running npm init command.Once your package.json file is created, you'll want to create the file that will be loaded when your module is required.
In that file, add a function as a property of the exports object. This will make the function available to other code.
exports.printMsg = function() {
  console.log("This is a node module that just prints this message");


Step 4: Publish your node module using below command
 npm publish
If you have not added any user to npm , above command will results in an error. So you must have added and logged in as  an npm user before step3.
npm adduser can be used for this.

Step 5: After publishing your node-module, you can access that in your other application as mentioned below,
1)Make a new directory outside of your project and cd into it
2) Run npm install <package>
3)Create a demo.js file which requires the package and calls the method
   var demo=require('testapp3');
   demo.printMsg();

4)Run node demo.js. The message should be output.








No comments:

Post a Comment