NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
How to work app.js file in NodeJs?
App.js file creates an express application object which set up the application with various settings and middleware. after that exports the app from the module.
First, we import some useful node libraries into the file using require(), including http-errors, express, morgan and cookie-parser and so on.
File Name :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
Then we require() modules from our routes directory. These modules/files contain code for handling particular sets of related "routes".
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
we create the app object using our imported express module, and then use it to set up the view (template) engine. There are two parts to setting up the engine. First, we set the 'views' value to specify the folder where the templates will be stored (in this case the subfolder /views). Then we set the 'view engine' value to specify the template library (in this case "pug").
File Name :
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// app.set('view engine', 'ejs');
The next set of functions call app.use() to add the middleware libraries for request handling chain.
express.json() and express.urlencoded() are needed to populate req.body with the form fields.
After these libraries we also use the express.static middleware, which makes Express serve all the static files in the /public directory in the project root.
File Name :
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
Routes
File Name :
app.use('/', indexRouter);
app.use('/users', usersRouter);
Note: The paths specified above ('/' and '/users') are treated as a prefix to routes defined in the imported files. So for example, if the imported users module defines a route for /profile, you would access that route at /users/profile. We'll talk more about routes in a later article.
The last middleware in the file adds handler methods for errors and HTTP 404 responses.
File Name :
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
The last step is to add it to the module exports (this is what allows it to be imported by /bin/www).
File Name :
module.exports = app;
app.render() :-
The app. render() method is used for returning the rendered HTML of a view using the callback function. This method accepts an optional parameter that is an object which contains the local variables for the view.
This method is similar to the res.render() function with the difference that it cannot send the rendered view to the client/user itself.
The res.render() function is used to render a view and sends the rendered HTML string to the client.
File Name :
app.render(view, [locals], callback)
Example
File Name :
var express = require('express');
var app = express();
var PORT = 3000;
// View engine setup
app.set('view engine', 'ejs');
// Without middleware
app.get('/user', function(req, res){
// Rendering home.ejs page
res.render('home');
})
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
File Name :
var express = require('express');
var app = express();
var PORT = 3000;
// View engine setup
app.set('view engine', 'ejs');
// With middleware
app.use('/', function(req, res, next){
res.render('User')
next();
});
app.get('/', function(req, res){
console.log("Render Working")
res.send();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Global Objects :-
some Global objects in Node.js are available in all modules.
File Name :
Error Handling :-
Node.js applications experience four types of errors.
File Name :
Errors in Node.js are handled through exceptions.
File Name :
File Name :
File Name :