Thursday, 6 October 2016

How to create simple javaScript Project for NodeJS Server

A. Creating Simple JavaScript Project using NodeJs Framework -

1. Open command Prompt and cd to New Folder

2. Run npm init
It will create package.json.
This file is main configuration file of nodeJs project.

New Folder is root directory.

3.Now install npm modules(JavaScript Libraries) using --> npm install
It will create npm_modules folder with js files defined in package.json

4.Create server.js file to create HTTP server.

Then hit http://localhost:8080/abc.

sample code -

var http = require("http");
http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
--------------------------------------->
Connection Issue - ECONNREFUSED;
Solution -
npm config set proxy  http://your_proxy_name:port

npm config set https-proxy https://your_proxy_name:port
npm config set proxy http://rilproxy2.rolta.com:8080 
npm config set https-proxy http://rilproxy2.rolta.com:8080


B. Creating Simple JavaScript Project using ExpressJS Framework -
This is as same as the above project creation.Only difference is that it gives us direct API to develop web app.
For ex.
In NodeJS Framework we have web  app after importing 'http' nodeJS API.
to create server, whereas in case of Express it gives same functionality with lesser code.We just need to import 'express' module to create server to handle http requests.

var express = require('express');
var app = express();

app.listen(3000,function(){
console.log("Express Framework is up and live at port 3000");
})

app.get('/',function(req,res){
res.send('Hello Express...');
})

C. Creating Simple JavaScript Project Skeleton using Express Generator -
 It helps to create full standard web application skeleton.

1 comment: