Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Food

console.log("I hunger for the taste of a proper meemey meal.");



function Drincc() {
    console.log("I have just one quiry, would you like a sprite cranberry?");
    console.log("Cranberry: Carbonated water, high-fructose corn syrup,natural flavors, citric acid, sodium citrate and sodium benzoate.");
}

function Eet() {
    console.log("Ravioli");
    console.log("1 pound ground beef,1 onion chopped, 4 cloves garlic minced,1 small green bell pepper diced, 1 (28 ounce) can diced tomatoes, 1 (16 ounce) can tomato sauce, 1 (6 ounce) can tomato paste, 2 teaspoons dried oregano, 2 teaspoons dried basil1 teaspoon salt, 1/2 teaspoon black pepper.");
}

console.log("C O N S O O M");

Drincc();


Eet(); 

ES6 RegExp exec()

var str = "Javascript is an interesting scripting language"; 
var re = new RegExp( "script", "g" ); 
var result = re.exec(str); 
console.log("Test 1 - returned value : " +  result);  
re = new RegExp( "pushing", "g" ); 
var result = re.exec(str); 
console.log("Test 2 - returned value : " +  result);

ES6 RegExp Prototype Sticky

var str = "Javascript is an interesting scripting language"; 
var re = new RegExp( "script", "g" ); 
re.test(str); 
console.log("Test 1 - Current Index: " +  re.lastIndex);  
re.test(str); 
console.log("Test 2 - Current Index: " + re.lastIndex) 

zcdvxbfcgnv

var connect = require('connect'),
    http = require('http');

var app = connect()
    .use(function(req, res, next) {
        console.log("That's my first middleware");
        next();
    })
    .use(function(req, res, next) {
        console.log("That's my second middleware");
        next();
    })
    .use(function(req, res, next) {
        console.log("end");
        res.end("hello world");
    });

http.createServer(app).listen(3000);

Execute Node.js Online

var http = require("http);

http.createServer()
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 https://127.0.0.1:8081/');

Node.js Hello World Example

/* Hello, World! program in node.js */
console.log("Hello, World!")

Execute Node.js Online

/* Simple Hello World in Node.js */
console.log("Hello World");

nodejs basics

/* Simple Hello World in Node.js */
/*Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js
Node.js = Runtime Environment + JavaScript Library */
/*
places where node js generally used==

I/O bound Applications
Data Streaming Applications
Data Intensive Real-time Applications (DIRT)
JSON APIs based Applications
Single Page Applications*/
console.log("Hello World");
/* node.js has 3 important component-
**IMPORT REQUIRED MODULES − We use the require directive to load Node.js modules.
**CREATE SERVER − A server which will listen to client's requests similar to Apache HTTP Server.
**READ REQUEST AND RETURN RESPONSE − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.
*/

/*================================================================================================================*/

/*var htp=require("http"); //vAariable name can be anything.
htp.createServer( function (request, response){
    response.writeHead(200, {'Content-Type' : 'text/plain'}); // here response have 3 steps first send header one where we send generelly success msg and other things then use write method call for complete response after that we end the response where
    response.end('Hello World');
}).listen(8081);
console.log('server rusdsdfsdfnning');*/


/*node package manager has 2 functionalities
**online repositories for node.js packages/module which are searchable on node.js.org.
**command line utility to install node.js package, do version management and dependency management on packages.
*/


/*call backing*/
/*var fs=require("fs");
var data=fs.readFileSync("nbvjfjfjv");
console.log(data.toString()); /// check in home in local machine.

var fs=require("fs");
fs.readFile("inuput.txt", function(err, data){
    if (err) console.log(err);
    console.log(data.toString());
});
console.log("finish it")*/


/*The first example shows that the program blocks until it reads the file and then only it proceeds to end the program.

The second example shows that the program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file.*/

/*means iof it call any function calling then it will not wait for response for function call it will got to next line to execute program*/



/*Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners as follows*/
/*var fs = require("fs");
var writeStream = fs.createWriteStream ("file.txt");//create a file name file.txt
writeStream.write("hi");
writeStream.write("I am avinash");
writeStream.end();




console.log("Hello Worlvjvjvjvvjd");

var fs = require("fs");

function readData (err, data){
    console.log(data);
}
fs.readFile('file.txt', 'utf8', readData);
*/

/**
 * Node FS Example
 * Node JS Write to File
 */
/*var fs = require("fs");

var writeStream = fs.createWriteStream("JournalDEV.txt");
writeStream.write("Hi, JournalDEV Users. ");
writeStream.write("Thank You.");
writeStream.end();


var fs = require("fs");

function readData(err, data) {
	  console.log(data);
}

fs.readFile('JournalDEV.txt', 'utf8', readData);

/*for in binary read*/
/*var fs = require("fs");

fs.readFile('JournalDEV.txt', function(err, data){
    console.log(data);
});
*/

/*create http server*/
 /*var http = require("http");
 var httpServer = http.createServer(function(request, response){
     console.log("request is running");
    
     response.write("hello client");
     
     response.end();
 });
 httpServer.listen(8001);*/
 /*when we hit https://localhost:8001/ in url we will get response */

/*You can explicitly queue any HTTP header in the response using the response.setHeader(name, value) member function*/

/****  response.setHeader(“Content-Type”, “text/html”);******/
/*To handle different kinds of Client Requests, we should add “Routings” to our HTTP Server.*/

/*http-server-simple-routing*/
/*var http = require("http");
var url = require("url");
var httpserver = http.createServer( function(request, response){
    var clientRequestpath = url.parse(request.url).pathname;
    switch (clientRequestpath){
        case "/":
            console.log("recieving a request: switch off");
            response.write("getting request from local server");
            break;
        default :
            console.log("recieving a request: switch default");
            response.write("getting request from  server");
            break;
    }
    response.end();
});
httpserver.listen(8001);
*/

/*event handler*/
/*var events = require("events");

var eventsEmitter = new events.EventEmitter(); // EVENT EMITTER WHO HANDLES ALL EVENTS PERFORM BY NODE.JS

eventsEmitter.emit("nameOfeventToCreate");  // IT CREATES AN EVENT.
eventsEmitter.on(nameOfeventToCreate, EventHandlerFunction); // IT BINDS TO EVENT WITH EVENT HANDLER.*/
/*on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.
So inside the emit function second parameter is not an event handler is it used to trigger the event*/



var x = function(a, b){ return a+b}; // this is called anonymous function where function doesn't have nam they are stored in a variable.
var y = x(4,4); 
console.log(y);

/*=====================================*/
/**
 * JournalDEV  
 * Nodes Events Demo
 */
var events = require("events");
var fs = require('fs');
var eventsEmitter = new events.EventEmitter();

eventsEmitter.on('read',readFileContent);
eventsEmitter.on('display',displayFileContent);
eventsEmitter.on('finished',finished);
eventsEmitter.emit('read','JournalDEV.txt');


function readFileContent(fileName){
    console.log("Reading " + fileName + " file started:");
    fs.readFile(fileName, 'utf8', readFile);
}

function  displayFileContent(data){
    console.log("File Data:");
    console.log(data);
    eventsEmitter.emit('finished');
}

function finished(){
  console.log("Reading and Printing File content job is done successfully.");
}

function readFile(err,data,fileName) {
    console.log("Reading " + fileName + " file done successfully.");
    eventsEmitter.emit('display',data);
}
	
	
	/* here for every event i have to trigger the event means fisrt i have trigger the readFileContent after thar when all readFileContent work has done then inside it i trigger display with data and after that inside displayFileContent i triggered finished */
	
	/* emit function argument are decided by the eventhandler function if eventhandler function required an argument then this argument is passed by the emit function when it is triggered */




/**************(EXPRESS MODULE)**************/
/*IT IS LIGHT WEB FRAMWORK TO DEVELOP NODE.JS WEB APPLICATION.
ABOVE WE HAVE SEEN HTTP SERVER USING "HTTP" MODULW, BUT WE CAN CREATE HTTP SERVER BY USING EXPRESS MODULE.IT SUPPORTS-
>Light-weight Web Application Framework
>It Supports Routings
>It supports Template Engines
>It supports File Uploading
>Develop SPA(Singe Page WebApplications)
>Develop Real-time Applications.

THIS HTTP SERVER MODULE IS CREATE BASIC CONNECTION TO CLIENT & SERVER BUT "CONNECT MODULE" USE ON TOP OF HTTP. INSIDE Connect WE CAN ADD ADDITIONAL FEATURE LIKE COOKIES. AND THIS EXPRESS IS USED ON TOP OF CONNECT TO USE SOME MORE EXTRA FEATURES.
Node JS Platform has another module : “express-generator”. Earlier “express-generator” module is part of “express” module only. But to provide clear modularity, they have separated into two modules.

What is Express Generator???????????

    Like Express JS, Express Generator is also a Node JS ModulE. It is used to quick start and develop Express JS applications very easily.

*/


/*to create express aaplication we need to hit some commonds-1
1- express ExpressSampleWebApp
2- cd ExpressSampleWebApp && npm install
3-SET DEBUG=ExpressSampleWebApp:* & npm start
4-To install (build) our application:
>>>npm install
5-To start our Express application:
>>>npm start


NOW IF U WILL CHECK "https://localhost:3000/" IN LOCAL MACHINE SERVER WILL START.
*/



/*============================================================================================================*/
/*util is used for better efficiency , .NET is used for socket programming*

THERE ARE TWO WAYS TO WRITE SEPERATE JS CODE FOR REUSABLE.
1- CREATE A JS FILE SAME AS MODULE NAME AND CODE THE MODULE.
2- CREATE A FoLDER SAME AS MODULE NAME AND WITHIN  THIS FOLDER CREATE A "INDEX.JS" WHICH CONTENTS CODE OF MODULE.
*/
/*
if we are using any function for reuse the attach that function with exports ex-
    expotrs.methodanmae= function(args){
        defn of Function
    }
    }

*/

/*exports.AuthenticateUser = function(userName, password){
    if (userName==="admin" && password==="admin"){
        return "valid User";
    }else{
        return "invalid User";
    }
}

*/
/*=================================================*/
/*module.exports = function(userName,password){  // inside DBModule foler file name index
	if (userName==="admin" && password==="admin"){
		return "valid User";
	} else{
		return "Invalid User";
	}
}
8/

/* this is httpserver.js outside folder*/
/*var module = require('./DBModule'); // this is foldername where all modeule are kept
var http = require("http");
var server = http.createServer(function(request, response){
	result=module("admin","admin"); // it is called invoke the module method inside the servercode and return the method response as server response.
	response.writeHead(200,{"Content-Type": "text/html"});
	response.end("<html><body><h1>I love my India"+result+"</h1></body></html>");
	console.log("Request received");});
server.listen(3000);
console.log("server is running");
*/
/*========================================*/
 /* how to handle form data in node.js WITH GET METHOD
  
  WE CAN HANDLE DATA SUBMITTED BY END USER A/C TO HTTP METHOD.
  THERE ARE TWO MODULE CALLED "URL", "QUERYSTRING"
  
  if WE USE GET METHOD THEN THE VALUE WILL DISPLAY IN ADDRESS BAR WITH THE URL
  */
  
/*=================WITH POST METHOD============*/
/*to handle post method we use data & end events on request object & querystring module
because in it data is sent along with request body*/


/*FOR GET METHOSD THERE IS NO NEED TO SPECIFY IT IN LOGIN PAGE BUT FOR THA POST METHOD WE HAVE TO SPECIFY METHOD IN POST..*/


/*=================================================================================================================*/
/*EVENT HANDLING in node js*/

/* BASED ON OUTCOMES IT IS BETTER  TO NOTIFY OUTCOMES BY EVENT AND THEN CALL OTYHER OTHET FUNCTION IN EVENT HANDLER GOR THIS WE NEED TO USED CUSTEM EVENT.
THESE CUSTEM EVENTS CAN BE CREATED BY EXTENDING FROM EVENT EMITTER OBJECTS*/

/*eventemitter is used to genertae events and javascript is used to call back function.
Event Handlers are JavaScript Asynchronous Callback Functions.
Event Loop will prepare results and send them back to the Client*/



/*==================BUFFER CLASS=======================*/
/*IT IS GLOBAL CLASS SO DON'T NEED TO IMPORT BUFFER TO USE IT.*/

var buf = new Buffer(100);  // this is buffer with size.
var buf1  = new Buffer([10,20,30,6,6,6,6,40,50]); //buffer which is containing array.
var buf2 = new Buffer("I am avinash chandra","utf-8");

console.log(buf1);
console.log(buf2);
/* output when just run above code=
<Buffer 0a 14 1e 06 06 06 06 28 32>
<Buffer 49 20 61 6d 20 61 76 69 6e 61 73 68 20 63 68 61 6e 64 72 61*/

len = buf2.write("i am ac");  // this method returns the (length of string/ size of buffer , which is lower) which we have written as a parameter. and it will overwrite the buffer value from starting
console.log(len);
var buf3 = new Buffer(5);
encode = buf3.write("dfvdfvdf");
console.log(encode);

console.log( buf2.toString()); // this function is used to read string which is stored in buffer.
    // the parameter should be encoding form like- utf-8,ascii
//console.log( buf.toString("bvhjxcbmhjxcb")); // this will give error.
console.log(buf2.toJSON()); // it is not work for buffer having array. that time it will print simple array can't change in json.


/* buffer supports concate, compare, copy, slice(substring of buffer), */

/*==================STREAM ==========================   */
/*Streams are objects that let you read data from a source or write data to a destination in continuous fashion. IT HAVE 4 TYPES-
1 READABLE- use for read stream
2 WRITABLE- write in stream
3 DUPLEX - for both read and write

4 TRANSFORM- A type of duplex stream where the output is computed based on input

*/

var fs = require("fs");
var data = 'Simply Easy Learning is the default kay for all resources';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
});

writerStream.on('error', function(err){
   console.log(err.stack);
});

console.log("Program Ended");



/*=============================================*/
var fs = require("fs");
var data = ''; // here only write data nothing else

/*data − This event is fired when there is data is available to read.

end − This event is fired when there is no more data to read.

error − This event is fired when there is any error receiving or writing data.

finish − This event is fired when all the data has been flushed to underlying system.*/




var readStream = fs.createReadStream('output.txt');
readStream.setEncoding('UTF8');
readStream.on('data', function(chunk){
    data += chunk;
});
readStream.on('end', function(){
    console.log(data);
});
readStream.on('error', function(err){
    console.log(err.stack);
});
console.log("Program Ended");

/*Duplex*/

var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");

/*transform*/

var fs = require("fs");
var zlib = require('zlib');

// Compress the file input.txt to input.txt.gz
fs.createReadStream('input.txt')
   .pipe(zlib.createGzip())
   .pipe(fs.createWriteStream('input.txt.gz'));
  
console.log("File Compressed.");


/* file system==================================*/

var fs = require("fs");
 var buf = new Buffer(1024);
console.log("Going to open file!");
fs.open("./input.txt", 'r+', function(err, fd) {
   if (err) {
      return console.log(err);
   }
   console.log("File opened successfully!");    

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ // this function only work when we have already open the file. after open function cal it works.

      if (err){
         console.log(err);
      }
      console.log(bytes + " bytes read");
      
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });   
});



/* JUST READ THE FILE*/
var fs = require("fs");

 //for call back
 fs.readFile("./input.txt", function(err, data){
	 if(err){
		 return console.log("error has occured");
	 }
	 console.log(data.toString());
 });
 
 // synchronized/* 
 var data = fs.readFileSync("./input.txt");
 console.log(data.toString());
// for Write
  fs.writeFile("./input.txt", "welcome to my world", function(err){
	 if (err){
		 console.error(err);
	 }
	console.log("it is saved");
 });

ES6 Array.prototype.entries Example2

var numbers = [1, 2, 3]; 
var val= numbers.entries(); 
console.log([...val]);

ES6 String Property Constructor

var str = new String( "This is string" ); 
console.log("str.constructor is:" + str.constructor)

Previous 1 ... 5 6 7 8 9 10 11 ... 90 Next
Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.