Nodejs Notes
Nodejs Notes
Both front-end and back-end can be programmed. Javascript is mostly used for manipulating DOM,
accessing cookies etc.
Objects like document, window and all the other objects APIs and modules, like the filesystem access functionality
that are provided by the browser are not present. are not present.
Node.js you control the environment as it runs on server Remote users may use different versions of browsers due
side. to which the functionality may differ.
You can write all the modern ES2015+ JavaScript that Browsers can be a bit slow to upgrade, sometimes on the
your Node.js web you are stuck with using older JavaScript /
ECMAScript releases
Node.js supports both the CommonJS and ES module Browsers are starting to see the ES Modules standard
systems. being implemented.
Installing Node.js
Checking Node.js installation
console.log(msg);
Building an HTTP Server
Build an HTTP Server
const http = require('http')
function sayHello(req,res)
{
res.statusCode = 200 //200 means success
res.setHeader('Content-Type', 'text/plain') //set up the response headers
res.write("Hello World")
res.end() //response packet will be sent back to the browser
}
On Console
On Browser Window
Reading file from file system
Reading files from the file system
Files stored locally on server-side can be read into a Node.js program.
The program can then process the file or send it to the client.
The control flow shall remain blocked until all file data has been read from
filesystem (file storage).
SYNTAX:
fs.readFileSync(filepath,encoding)
Assume a HTML file stored on server-side
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>About India</title>
</head>
<body>
India, officially the Republic of India is a country in South Asia. It is the
seventh-largest country by area, the second-most populous country, and the most populous
democracy in the world. Bounded by the Indian Ocean on the south, the Arabian Sea on the
southwest, and the Bay of Bengal on the southeast, it shares land borders with Pakistan to
the west;[f] China, Nepal, and Bhutan to the north; and Bangladesh and Myanmar to the east.
In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives; its Andaman
and Nicobar Islands share a maritime border with Thailand, Myanmar, and Indonesia. The
nation's capital city is New Delhi.
</body>
</html>
Reading File (Synchronously)
const http = require('http')
const fs = require('fs')
SYNTAX:
fs.readfile(filepath,encoding, callbackfunction)
Reading File (Asynchronously)
const http = require('http')
const fs = require('fs')
function sayHello(req,res){
res.statusCode = 200 //200 means success
res.setHeader('Content-Type', 'text/plain') //set up the response headers
res.write("Hello World")
res.end() //response packet will be sent back to the browser
Output on console
const http = require('http')
const hostname = '127.0.0.1' //local machine, this computer
const port = 8080 //port number where the server will receive requests
function sayHello(req,res){
res.statusCode = 200 //200 means success
res.setHeader('Content-Type', 'text/plain') //set up the response headers
res.write("Hello World")
res.end() //response packet will be sent back to the browser
}
process.on('SIGTERM',()=>{
server.close(()=>{
console.log("Server Exiting")
})
})
1
3
2 4
ExpressJS
Express is a node js web application framework that provides broad features for
building web and mobile applications. It is used to build a single page, multipage, and
hybrid web application. It's a layer built on the top of the Node js that helps manage
servers and routes.
app.get('/',(req,res) => {
res.send("Hi!")
})
app.listen(3000,()=>console.log('Server ready'))
Output
ExpressJS: Routing and Handling GET and POST requests
const express = require('express')
const fs = require('fs')
app.get('/',(req,res) => {
res.write('<h1><a href="showsignin">Sign-In</a></h1>')
return res.end();
})
app.listen(3000,()=>console.log('Server ready'))
Contd.
app.get('/showsignin',(req,res) => {
res.write(data);
return res.end();
});
})
Contd.
app.post('/dosignin',(req,res) => {
var body = ''
req.on('data', function (data) {
body += data //collecting the request data in the body variable
})
req.on('end', function () {
res.write("<h1>Sign-In Successful</h1>")
else {
res.write("<h1>Sign-In Failed</h1>")
res.end()
})
})
Node.js: Connecting to MySQL
MySQL module
Mysql module can be installed using the following command:
SYNTAX:
con.connect(callback function to be called when connection is created)
EXAMPLE:
con.connect(function (err) {
if (err) throw err;
//do something
})
Executing a query
SYNTAX:
con.query(query-string, [comma separated query-parameters], callback-function)
EXAMPLE:
console.log(result);
if (result.length == 1) {
res.write("<h1>Sign-In Successful</h1>")
res.end()
} else {
res.write("<h1>Sign-in Failed</h1>")
res.end()
}
});
Other popular frameworks
● React: A JavaScript library for building user interfaces
● AngularJs: AngularJs is a JavaScript open-source front-end framework that is
mainly used to develop single-page web applications(SPAs). It extends HTML
DOM with additional attributes and makes it more responsive to user actions.
● And many more
Thank You