Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





What is app.js file in node.js?

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.

  • __dirname :- specifies the name of the directory that contains the code of the application.
  • __filename :- specifies the filename of the code.
  • Exports :- a reference to the module.exports shorter to type
  • module :- a reference to the current module.
  • require :- used to import module, local files and json files.
  • File Name :


    Error Handling :-

    Node.js applications experience four types of errors.

  • Standards Javasript Error
  • system error
  • user specific error
  • Assertion error
  • File Name :

    Errors in Node.js are handled through exceptions.





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here