Sunday, 30 September 2018

node.js: Hello World Web application

In this post, I am going to explain how to develop simple web application using node.js framework.

Step 1: Import required modules. I am using http module to develop ‘Hello World’ application.

/* Import http module */
var http = require("http");

‘require’ directive is used to import the modules.

Step 2: Create the server.
http.createServer(function (request, response) {
        
         response.writeHead(200, {'Content-Type': 'text/plain'});

         response.end('Hello World\nWelcome to node.js programming');
        
}).listen(8080);

As you see above snippet,
a.   Server instance listens on port 8080
b.   I am sending the response code as 200
c.   I am setting response type as text/plain
d.   Sending response message to client

Complete application looks like below.

HelloWorld.js
/* Import http module */
var http = require("http");

/* Create the server, that listens on port 8080 */
http.createServer(function(request, response) {

 response.writeHead(200, {
  'Content-Type' : 'text/plain'
 });

 response.end('Hello World\nWelcome to node.js programming');

}).listen(8080);


Run the application by executing the statement ‘node HelloWorld.js’.

Hit the url ‘http://localhost:8080/’, you can able to see below screen.



Previous                                                 Next                                                 Home

Node.js Hello World Application

hello-world.js
/* Hello World! program in Node.js */
console.log("Hello World!");

Execute the statement ‘node hello-world.js’

C:\>node hello-world.js
Hello World!

Note
In Node.js, it is considered as good style to use hyphens (-) or underscores (_) to separate multiple words in filenames.



Previous                                                 Next                                                 Home

Node.js: Installation and setup

Go to below location and download node.js software.

At the time of writing this post, 10.9.0 is the latest version of node.js library.

Installing node.js on windows
Double click on the downloaded executable file.


Click on Next button.


Accept the license agreement and click on Next button.

By default, nodejs installs at C:\Program Files\nodejs, you can change the installation location by clicking on ‘Change…’ button.


Click on Next button.


Click on Install button.


Once the installation is successful, you can see below kind of screen.


Click on Finish button.


Go to the node.js installation directory, you can see below kind of directories structure.


The installer sets the C:\Program Files\nodejs directory in window's PATH environment variable.

Open new command prompt and execute the command ‘node –version’ to know the node version.

C:\>node --version
v10.9.0

That’s it, you are done with setting up node installation.

Reference

Previous                                                 Next                                                 Home

Introduction to Node.js

Node.js is designed to build scalable network applications. Node.js runtime environment contains everything that you need to run a program written in Javascript.

What is Chrome's V8 JavaScript engine?
Node.js is JavaScript run time built on top of Chrome's V8 JavaScript engine. V8 is Google’s open source high-performance JavaScript engine, written in C++ and used in Google Chrome, and in Node.js.

If you are from Java background, below analogy can help you.




Is Node.js support Asynchronous model?
Yes, Node.js is an asynchronous event driven JavaScript runtime.

Why Node.js?
a.   Node.js uses an event-driven, non-blocking IO model that makes it light weight, efficient and scalable.
b.   Node.js supports Non-blocking I/O. In case of blocking I/O, if user requests for 2 IO calls, second IO call will not start until first IO call is finishes. But in case of Non-Blocking I/O, both the I/O requests start parallelly.

In Node.js, all APIs are non-blocking.

c.   Node.js is open source, applications developed in node.js can run in different platforms like windows, linux and Mac OS.
d.   Node.js has a package manager called npm, it is used to access all the node.js libraries.
e.   Node.js is asynchronous and single threaded. All the events are recorded in event queue and handled in the order they were raised

What you should know?
a.   Since node.js is a JavaScript framework, you must know JavaScript to start with.

Previous                                                 Next                                                 Home

node.js tutorial

Introduction

Introduction to Node.js
Installation and setup
Hello World Application
REPL: Exit from the prompt
REPL: list all the commands
Exploring node package manager (npm)
npm: Global vs local installation of modules
npm: Adding dependencies to node.js application
What is npmjs?
Node.js: Callback example

Node.js: Global Objects

Global Objects
Exploring console object
    Evaluate the expressions in console messages
    console.assert(value[, ...message])
    console.clear(): Clear the messages on terminal
    console.count([label]): Maintains internal counter for the label
    console.countReset([label]): Reset the counter for this label
    console.debug(data[, ...args])
    console.dir(obj[, options])
    console.dirxml(...data): Logs the information
    console.error([data][, ...args])
    console.group([...label]): logs message with indentation
    console.groupCollapsed(): Log the messages with indentation
    console.groupEnd(): Decreases the indentation while logging
    console.info([data][, ...args]): logs the message
    console.log([data][, ...args]): logs the message
    console.table(tabularData[, properties]): logs table data
    console.time([label]): Compute the duration of an operation console.time([label])
    console.timeEnd([label]): Stops a timer
    console.timeLog([label][, ...data]): Print the elapsed time
    console.trace([message][, ...args]): Log the stack trace
    console.warn([data][, ...args]): Log warning message
__dirname: Get the directory name of current module
__filename: Absolute path of the current module file
require(): Load required modules
Process object
    process.stdout: Write to standard output
    process.stdin: Read input
    process.exit: Exit current process
timing functions
process.stdout clearLine() and cursorTo methods

Core Modules

Introduction to Core Modules
Exploring readline module
    readline: close event
    readline: line event
    readline : pause event
    readline: resume event
    readline: SIGINT event
    Readline: close method
    Readline: pause method
    Readline: rl.prompt([preserveCursor])
    readline: rl.question(query, callback)
    readline: rl.setPrompt(prompt)
    readline: rl.write(data[, key])
    readline.clearLine(stream, dir)
    readline.clearScreenDown(stream)
    readline.createInterface(options)
    readline.createInterface(options): How to use completer function?
    readline.cursorTo(stream, x, y)
    readline.emitKeypressEvents(stream[, interface])
    readline.moveCursor(stream, dx, dy)
    readline: Building simple command line interface
    readline: How to read a file
Exploring events module
    Implementing custom event emitter
    asynchronous and synchronous way of calling listeners
    emitter.once(eventName, listener): Handle the event only once
    Error handling of events
    Exploring EventEmitter class
        newListener event
        removeListener event
        How to set the maximum listeners for specific emitter instance?
        emitter.addListener(eventName, listener): Add listener to this event
        emitter.emit(eventName[, ...args])
        emitter.eventNames()
        emitter.getMaxListeners()
        emitter.listenerCount(eventName)
        emitter.off(eventName, listener)
        emitter.on(eventName, listener)
        emitter.once(eventName, listener)
        emitter.prependListener(eventName, listener)
         emitter.prependOnceListener(eventName, listener)
        emitter.removeAllListeners([eventName])
        emitter.removeListener(eventName, listener)
        emitter.setMaxListeners(n)
        emitter.rawListeners(eventName)
Exporting custom modules
Error-first callbacks
Working with file system (fs) module
    fs.readdirSync(path[, options]): list all the files in a directory
    readdir(path[, options], callback): list files asynchronously
    readFileSync(path[, options]): Return the contents of the file
    fs.readFile(path[, options], callback): Read file asynchronously
    child_process.exec(command[, options][, callback]) : Execute system commands
    fs.statSync(path[, options]): get the statistics or information about a file
    fs.writeFileSync(file, data[, options]): Write data to the file
    fs.writeFile(file, data[, options], callback): Write data to a file asynchronously
    fs.appendFileSync(path, data[, options]): Append data to a file synchronously
    fs.appendFile(path, data[, options], callback): Append data to a file synchronously
    fs.existsSync(path): Check for the existence of a file
    fs.mkdirSync(path[, mode]): Creates a directory synchronously
    fs.mkdir(path[, mode], callback): Create a directory asynchronously
    fs.renameSync(oldPath, newPath): Rename a file
    fs.rename(oldPath, newPath, callback): Rename the file asynchronously
    fs.unlinkSync(path): Remove a file or symbolic link asynchronously
    fs.unlink(path, callback): Remove a file or symbolic link asynchronously
    fs.rmdirSync(path): Remove a directory synchronously
    fs.rmdir(path, callback): Remove a directory asynchronously
    Recursively remove a directory
    fs.createReadStream(path[, options]): Create readable stream
    fs.createWriteStream(path[, options]): Working with Writeable stream
Working with http module
    Make http request
    http.createServer([options][, requestListener]): Building Hello World web application
    http: Serve files
    Serving html page
    Load json file using require function
    http: Handle post requests

Miscellaneous

child_process.spawn(command[, args][, options]): Spawns a new process
Node cli: --trace-warnings

Previous                                                 Next                                                 Home

JavaScript: Event handling

JavaScript provides very good support for event handling like mouse clicks, keyboard clicks etc., in simple terms, you registers a function on specific event. Whenever that event happens, the registered function executes the code.

How to assign an event handler to an element
There are many ways to assign event handler to an element.
a.   As an attribute in html tag
b.   Using a DOM-object property

As an attribute in html tag
<input type="button" onclick="goodMorning();" value="Good Morning" />

As you see above statement, Whenever you click the button onClick, it calls the function goodMorning().

Following is the complete working application.

process.js
function goodMorning(){
 alert("Good Morning");
}

function goodAfternoon(){
 alert("Good Afternoon");
}

function goodNight(){
 alert("Good Night");
}


events.html
<!DOCTYPE html>

<html>

<head>
    <title>Accessing style properties</title>
    <script src="process.js"></script>
</head>

<body>
    <input type="button" onclick="goodMorning();" value="Good Morning" />
    <input type="button" onclick="goodAfternoon();" value="Good Afternoon" />
    <input type="button" onclick="goodNight();" value="Good Night" />
</body>

</html>


Using a DOM-object property
document.getElementById("morning").onclick = goodMorning;

Above statement gets an element with if ‘morning’ and calls the function goodMorning when mouse clicks on it.

process.js

function goodMorning(){
 alert("Good Morning");
}

function goodAfternoon(){
 alert("Good Afternoon");
}

function goodNight(){
 alert("Good Night");
}

function initEvents(){
 document.getElementById("morning").onclick = goodMorning;
 document.getElementById("afternoon").onclick = goodAfternoon;
 document.getElementById("night").onclick = goodNight;
}

window.onload = initEvents;


events.html

<!DOCTYPE html>

<html>

<head>
    <title>Accessing style properties</title>
    <script src="process.js"></script>
</head>

<body>
    <input type="button" id="morning" value="Good Morning" />
    <input type="button" id="afternoon" value="Good Afternoon" />
    <input type="button" id="night" value="Good Night" />
</body>

</html>



Previous                                                 Next                                                 Home

Changing the styles using JavaScript DOM

In my previous post, I explained how to access styles associated with an element. By using DOM, you can also set the style values.

Syntax
element.style.property = value;

process.js
function processData(){
 var para = document.getElementById("paragraph1");
 
 para.style.color = "red";
 alert("Color : " + para.style.color);
 
 para.style.backgroundColor = "white";
 alert("Background color : " + para.style.backgroundColor);
}

window.onload = processData;


styleAccess.html
<!DOCTYPE html>

<html>
 <head>
  <title>Accessing style properties</title>
  <script src="process.js"></script>
 </head>
 
 <body>
  
  <p id="paragraph1" style="color:white; background-color:black;">
   JavaScript is fun to learn
  </p>
 </body>
</html>



Previous                                                 Next                                                 Home

JavaScript: getting inline styles attached to an element

By using 'element.style.propertyName', you can get the styles attached to given element (Only inline styles, not external and embedded styles information).

If any property has minus (-) sign in it, you have to access the property value using camel case like 'element.style.fontFamily'.

For example,
font-size should be used like fontSize
font-family should be used like fontFamily

process.js
function processData(){
 var para = document.getElementById("paragraph1");
 alert("Color : " + para.style.color);
 alert("Background color : " + para.style.backgroundColor);
}

window.onload = processData;


styleAccess.html
<!DOCTYPE html>

<html>

<head>
    <title>Accessing style properties</title>
    <script src="process.js"></script>
</head>

<body>

    <p id="paragraph1" style="color:white; background-color:black;">
        JavaScript is fun to learn
    </p>
</body>

</html>





Previous                                                 Next                                                 Home

JavaScript: insertAfter: Insert element after an element

In this post, I am going to implement insertAfter function used to insert an element after given element.

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Following is the complete working application.

process.js
function addData(){
 var para = document.createElement("p");
 var text = document.getElementById("text").value;
 var textNode = document.createTextNode(text);
 para.appendChild(textNode);
 
 var targetElement = document.getElementById("myButton");
 
 insertAfter(para, targetElement);
}

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}


changeDom.html
<!DOCTYPE html>

<html>
 <head>
  <title>Change DOM</title>
  <script src="process.js"></script>
 </head>
 
 <body>
  
  <div id="data1">
   <input type="text" id="text"/><br />
   <input type="button" id="myButton" value="click me" onclick="addData();" />
  </div>
 </body>
</html>



Previous                                                 Next                                                 Home

JavaScript: insertBefore: Insert element before an element

‘insertBefore’ method is used to insert an element before given element.

Syntax
parentElement.insertBefore(newElement, targetElement);

Above statement insert newElement before targetElement.

process.js
function addData(){
 var para = document.createElement("p");
 var text = document.getElementById("text").value;
 var textNode = document.createTextNode(text);
 para.appendChild(textNode);
 
 var targetElement = document.getElementById("welcomeMsg");
 
 var div = document.getElementById("data1");
 div.insertBefore(para, targetElement);
}

changeDom.html

<!DOCTYPE html>

<html>

<head>
    <title>Change DOM</title>
    <script src="process.js"></script>
</head>

<body>

    <div id="data1">
        <input type="text" id="text" />
        <br />
        <input type="button" id="welcomeMsg" value="click me" onclick="addData();" />

    </div>
</body>

</html>


Previous                                                 Next                                                 Home

JavaScript: createTextNode: Create text node

createTextNode method is used to create a text node.

Syntax
document.createTextNode(text);

Example
document.createTextNode("Good Morning");

process.js
function addData(){
 var para = document.createElement("p");
 var textNode = document.createTextNode("Good Morning");
 para.appendChild(textNode);
 
 var div = document.getElementById("data1");
 div.appendChild(para);
}


changeDom.html
<!DOCTYPE html>

<html>

<head>
    <title>Change DOM</title>
    <script src="process.js"></script>
</head>

<body>

    <div id="data1">
    </div>

    <input type="button" value="click me" onclick="addData();" />

    </div>
</body>

</html>

Open changeDom.html in browser, it shows the button ‘cilck me’. For every click of the button, it adds new paragraph with text "Good Morning" to the browser window.


Previous                                                 Next                                                 Home

JavaScript: appendChild: Create a child to node

By using ‘appendChild’ method, you can add a child to parent node.

Syntax
parentNode.appendChild(childNode);

process.js
function addData(){
 var para = document.createElement("p");
 var textNode = document.createTextNode("Good Morning");
 para.appendChild(textNode);
 
 var div = document.getElementById("data1");
 div.appendChild(para);
}


changeDom.html
<!DOCTYPE html>

<html>

<head>
    <title>Change DOM</title>
    <script src="process.js"></script>
</head>

<body>

    <div id="data1">
    </div>

    <input type="button" value="click me" onclick="addData();" />

    </div>
</body>

</html>

Open changeDom.html in browser, it shows the button ‘cilck me’. For every click of the button, it adds new paragraph with text "Good Morning" to the browser window.







Previous                                                 Next                                                 Home

JavaScript: createElement: Create new Element

By using createElement method, you can create an element.

Syntax
document.createElement(nodeName);

Example
document.createElement("p");

Above statement creates a paragraph element.

process.js
function addData(){
 var para = document.createElement("p");
 var textNode = document.createTextNode("Good Morning");
 para.appendChild(textNode);
 
 var div = document.getElementById("data1");
 div.appendChild(para);
}

changeDom.html
<!DOCTYPE html>

<html>

<head>
    <title>Change DOM</title>
    <script src="process.js"></script>
</head>

<body>

    <div id="data1">
    </div>

    <input type="button" value="click me" onclick="addData();" />

    </div>
</body>

</html>

Open changeDom.html in browser, it shows the button ‘cilck me’. For every click of the button, it adds new paragraph with text "Good Morning" to the browser window.



Previous                                                 Next                                                 Home