Nodejs Notes
Nodejs Notes
Nodejs Notes
• Node.js is free
• NodeDemo.js
var http = require('http');
Step 2:
Go to Command Prompt and to the directory where
the file is saved.
Steps to create and run a Node.js File
Step 3: Run the file using the following command
node NodeDemo.js
• 1st argument is the status code, 200 --> all is OK, 2nd argument is an
object containing the response headers.
Node Package Manager
• NPM (Node Package Manager) is the default package
manager for Node.js and is written entirely in Javascript.
Developed by Isaac Z. Schlueter, it was initially released
in January 12, 2010.
• NPM manages all the packages and modules for Node.js
and consists of command line client npm. It gets installed
into the system with installation of Node.js. The required
packages and modules in Node project are installed using
NPM.
Installing NPM:
• To install NPM, it is required to install Node.js as NPM
gets installed with Node.js automatically.
Program:
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
/*Use our upper-case module to upper case
a string:*/
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Output:
Modular Programming in Node JS
Core Modules: Node.js has many built-in modules that are part
of the platform and comes with Node.js installation. These
modules can be loaded into the program by using the require
function.
Program:
Output:
Modular Programming in Node JS
Filename: calc.js
Since this file provides attributes to the outer world via exports,
another file can use its exported functionality using the require()
function.
Filename: index.js
Output:
Program:
//File Name: index.js
• Read Files:
The fs.readFile() method is used to read files on your
computer.
File Operations in NodeJS
• //FileName: demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
• Program:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
File Operations in NodeJS
Output:
• Create Files:
The File System module has methods for creating new files:
1.fs.appendFile()
2.fs.open()
3.fs.writeFile()
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function
(err) {
if (err) throw err;
console.log('fs.appendFile() Method Appiled');
});
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('fs.open() Method Appiled');
});
fs.writeFile('mynewfile3.txt', 'Hello content!', function
(err) {
if (err) throw err;
console.log('fs.writeFile() Method Appiled');
});
Output:
File Operations in NodeJS
• Delete Files:
To delete a file with the File System module, use the fs.unlink() method.
The fs.unlink() method deletes the specified file.
• Rename Files:
To rename a file with the File System module, use the fs.rename() method.
The fs.rename() method renames the specified file.
Program:
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err)
{
if (err) throw err;
console.log('File Renamed!');
});
Output:
Express Development Environment
We can install it with npm. Make sure that you have Node.js and npm
installed.
Step 1: Creating a directory for our project and make that our
working directory.
$ mkdir gfg
$ cd gfg
Step 2: Using npm init command to create a package.json file for our
project.
$ npm init
Route Method:
The application object has different methods corresponding to each of
the HTTP verbs (GET,POST, PUT, DELETE). These methods are
used to receive HTTP requests.
Defining a route:
Below are the commonly used route methods and their description:
Method Description
get() Use this method for getting data from the server.
post() Use this method for posting data to a server.
put() Use this method for updating data in the server.
delete() Use this method to delete data from the server.
all() This method acts like any of the above methods. This can be used
to handle all requests.
routing.get("/notes", notesController.getNotes);
routing.post("/notes", notesController.newNotes);
routing.all("*", notesController.invalid);
notesController is the custom js file created to pass the navigation to this
controller file. Inside the controller, we can create methods like
getNotes,newNotes, updateNotes.
Handling Routes:
Program:
const express = require('express')
const app = express()
app.all((req, res, next) => {
console.log('Accessing the secret section ...')
next()
})
app.get('/', (req, res) => {
res.send('hello world') })
app.get('/home', (req, res) => {
res.send('home page')
})
app.get('/*', (req, res) => {
res.send('error 404 page not found')
})
app.post('/', (req, res) => {
res.send('POST request to the homepage')
})
app.listen(8080, () => {
console.log('server started on port 8080')
})
Handling Routes:
Output:
Routing and Query Parameters
In Express.js, you can directly use the req.query() method to access the string
variables. As per the documentation, the req.param method only gets the route
parameters, whereas the req.query method checks the query string parameters.
Program:
var express = require('express');
var app = express();
var PORT = 3000;
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Routing and Query Parameters
Output:
the request method and request URL before the handler executes. The route
definition for which we want to add the middleware.
app.get('/login', myController.myMethod);
res.send('/login’);
};
Program:
Route1.js file
const express = require('express');
const router = express.Router();
const myController =
require('../Controller/myNotes1');
router.get('/', myController.myMethod);
router.get('/about', myController.aboutMethod);
module.exports = router;
myNotes.js File
exports.myMethod = async (req, res, next) => {
res.send('<h1>Welcome</h1>');
};
exports.aboutMethod = async (req, res, next) => {
res.send('<h1>About Us Page</h1>');
};
app.use(mylogger);
app.use('/', router);
app.listen(3000);
console.log('Server listening in port 3000’);
Output:
Types of Middlewares
• Application-level middlewares
Application-level middlewares are functions that are associated with the
application object. These middleware function will get executed each time an
application receives a request.
• Router-level middlewares
Router-level middlewares are functions that are associated with a route. These
functions are linked to express.Router() class instance.
• Router-level middleware
Router-level middleware works in the same way as application-level
middleware, except it is bound to an instance of express.Router().
• Error-handling middleware
Error-handling middleware always takes four arguments. You must
provide four arguments to identify it as an error-handling middleware
function. Even if you don’t need to use the next object, you must
specify it to maintain the signature. Otherwise, the next object will be
interpreted as regular middleware and will fail to handle errors.
• Built-in Middleware:
Express has the following built-in middleware functions:
o express.static serves static assets such as HTML files, images,
and so on.
o express.json parses incoming requests with JSON payloads.
o express.urlencoded parses incoming requests with URL-
encoded payloads.
• Third-party middleware
Use third-party middleware to add functionality to Express apps.
Install the Node.js module for the required functionality, then load it in
your app at the application level or at the router level.
Program:
const express = require('express')
const app = express()
const router = express.Router()
// Application-level middleware
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
// Router-level middleware
router.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
app.use('/', router)
// error handler
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
// Third-party middleware
const cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
app.use(cookieParser())
Chaining middlewares
• Middlewares can be chained.
• We can use more than one middleware on an Express app instance, which
means that we can use more than one middleware inside app.use() or
app.METHOD().
• We use a comma (,) to separate them.
Program:
var express = require('express');
var app = express();
app.listen(PORT, ()=>{
console.log("app running on port "+PORT)
})
Connecting to MongoDB with Mongoose
Connecting to MongoDB with Mongoose – Introduction
Organizations use various databases to store data and to perform
various operations on the
data based on the requirements.
Some of the most popular databases are:
•Cassandra
•MySQL
•MongoDB
•Oracle
•Redis
•SQL Server
A user can interact with a database in the following ways.
•Using query language of the respective databases' - eg: SQL
•Using an ODM(Object Data Model) or ORM(Object-Relational
Model)
Introduction to Mongoose Schema
A schema defines document properties through an object, where the
key name corresponds to the property name in the collection. The
schema allows you to define the fields stored in each document along
with their validation requirements and default values.
• Data validation is important to make sure that "invalid" data does not
get persisted in your application. This ensures data integrity.
Syntax:
const Model = mongoose.model(name ,schema)
CRUD OPERATIONS
communications.
Generate the SSH keys in the server where the application will be
running.
Session Management,Cookies
Session Management is a technique used by the webserver to store a
particular user's session information. The Express framework provides
a consistent interface to work with the session-related data. The
framework provides two ways of implementing sessions:
• By using cookies
• Stylus compiles down to standard CSS and can be used in any web
project.