How to check Speed(performance) view engines [pug/ejs/html] - html

I'm trying to make Web-Server with Node.js.
First of my project using pug for view engine.
But, Web-Designer gives me html, but it's syntax is too different from pug.
So, I want to change my project as html or ejs. (I think ejs is similar to html)
(I don't know how to set view engine ~~.html, so I use ejs)
(But I'm not sure this way is right, under paragraph)
First, I generate new repository with express --no-view.
I set view engine in app.js like under,
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
Now, I have some question for speed(performance) between [EJS, PUG, pure HTML].
I think render speed is HTML > EJS > PUG, but I have no ideas for check this performance.
I need advice. Any Guess, Link, Answers can help me.
Thanks to read my question.

Short Answer:
EJS : 900-1200 request per second
HTML: 6000 request per second and 12000 with some customizations
Long Answer:
I made a simple test and I've got with express about 6000 request in a second with pure HTML and got about 12000 request per second by storing the HTML in a variable and send it to the client and tried with ejs I've got 900-1200 request per second
But the results may change by the way your code works and how your html/ejs file is written could change the results

Related

Is it not proper to use the send method to return HTML? Express

I am playing with express, in the past I have used echo with PHP to render out lines of html. In node/express I can add html to a variable and use res.send to return html. That way I can run loops and other things right in the function returning that route. Is this method bad practice? Below I have an example that counts to four.
var router = express.Router();
let a = (req, res, next) => {
let send = `<html>`;
for (let i = 0; i < 5; i++) {
send += `${i}`;
}
send += `</html>`;
res.send(send);
//res.download(filepath)
}
router.get('/', [a]);
module.exports = router;
I think this is a way to go about express router but it's probably not the easiest and it would cause a lot of code on your router page. It all depends on how large and scalable you want your project to be. If you are looking at doing a smaller project then this would work but if you were doing something a little larger e.g. e-commerce site then I would say put your html files in a separate folder and create a views directory for express. I would also suggest using an open source JavaScript Framework such as ReactJS, Vue, or ejs to name a few. You would have to do more code to your express server by adding views as seen in this link
Adding views in express
So instead of sending the html you would do something like res.render('/home'); if that is what you called your home page in your views file.
If that didn't answer your question please let me know.

How do I use Nodejs for backend using SQL workbench?

I am a beginner and this is my first full-stack web development project and I have completed the front-end part and created the related tables using MySQL... and now I want to link the tables to front-end using nodejs. How do I proceed further?? Is it proper to use workbench in the first place for a full-stack project?? Please guide me.
SQL Workbench is just an IDE for mySQL so thats fine for building out your DB, setting permissions etc.
Your question is not one that is simple to answer, simply because the steps in creating, setting up a full web app is not that simple to explain..
There are few things you will need to do to hook this up
Ensure you have a mySQL middleware installed
Ensure you have the routes created
Use a templating engine like EJS
Once you have the basic flow working ( meaning you can hit your page and it returns the correct page ) you will want to then hook into the DB before sending the response object back to the browser. A typical flow would be, on your 'get' response, you would perform the mysql 'select'
This should be promis based but will depend on the actual package you install, I don't use mysql but a postgres command is something like
query.pool("SELECT is, name, des from table where id = '10' ").then(results => {
//put in your response code here to send back to the page
}).catch( e => {console.error(e)})
The response code portion is where you would send things back to the page, in an ejs template would then be able to access the response and display the data.
I know, this is a bit light on full explanations and that is because the proper response would be huge!
Judging by the question I would guess you are a bit new to node / DB etc ( sorry if you are not ) I think what may be very helpful is to watch a few youtube videos on setting up Node and EJS ( or any templating engine for that matter )
That should give you the basic understanding and setup of the project.

Csrf fix in node js at page level

I looked at csrf implementation in node js Git hub example and was wondering this is for a application level. What if I want to apply it on one or two pages in the application. I did not find any example on the web. I know that in asp.net you can do it but not sure how the same can be achieved in Node JS.
Any help in guiding to a solution is greatly appreciated.
Add the csruf middleware on the routes which you want to protect. Like the example in the Github link shows:
app.get('/route/to/protect', csrfProtection, function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
This will allow csrf only for this route and not others. You can also use Regex to match routes as explained in the express docs.

Universal routing with express and react router. Understanding history behaviour

I am using React Router 4.0 and Express 4.14 to create an app that has a mix of single-page-app (SPA) and multi-page-app (MPA). I don't know if that's good practice, but this is not the point. I am actually doing it to learn rather than for a real world app. This idea comes from the scenario where you have strongly separated sections inside an app, as for example a blog and a portfolio.
Client side
So, when I want to navigate as a SPA, I use the Link component from react-router-dom, like <Link to="/reactrouter-route">. If I want to make a request to a route handled by the server, I use <a href="/server-route">.
Server side
I have a middleware logging the path of any request received by my server. I define two routes, each serving a complete SPA. To keep with the blog/portfolio example, imagine I have the following
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(req.path);
next();
});
app.get('/', (req, res) => {
res.sendFile('blog.html');
});
app.get('/portfolio', (req, res) => {
res.sendFile('portfolio.html');
});
Behaviour
When I go to / the blog gets loaded as a SPA and I can go to the different posts navigating back to / when I want. Everything works as expected. All this navigation inside the SPA is managed by React Router, and the server only gets the first request to /.
Imagine that from a specific post, say /posts/some-post, I have a link to the portfolio. If I click it, I get a request at the server, and it responds with the portfolio SPA. I can navigate inside the portfolio SPA, but I cannot go back to /posts/some-post. I get the following error:
Cannot GET /posts/some-post
I thought the error was thrown by the server, but surprisingly I don't get any request when going back. I only get requests at the server when going forward through a link (only with <a>).
I kept doing tests and there is no problem if I go back from /portfolio to /. This works as expected.
It gets interesting
I defined a route in my server with just the same rule that I had in my React Router routes. The path I was matching in this new route was /posts/:postid. I set this route to redirect to /. Now, I get the same error if I go from posts/some-post to /portfolio and I try to come back. This is not strange as the server doesn't get a request. It's also normal that I reach / if I go straight to /posts/some-post by typing in the URL in the browser.
But, once I go to /posts/some-post manually, I can go from /portfolio back to /posts/some-post without the error. Now it behaves as if the server was called. In fact, I get a request in the server to fetch the static files. However, I don't get a request to /posts/some-post nor /.
Even then, I would get an error if a go from /posts/some-other-post to /portfolio and try to go back.
Question
I guess this has to do with the cache, but I don't know what is going on there. When is the React Router handling going back? When is the server handlin it? How is the cache involved in this process?
It sounds like you need a clearer mental model of the roles of the server and the client in an SPA. "Single Page" is the important part.
The client, built with React, should never be loading pages from the server. It should be a "single page". In other words, you should not be using <a href="/server-route"> in your client app at all. The client should only get (JSON) data from the server using something like fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
I highly suggest you check out Create React App which also explains how to integrate with a node API backend during development. Basically you want all your client routes to be something like /post/:postid which will be handled by React Router and then that React component would use fetch to get the data from something like /api/posts/10. If you use /api to prefix all your requests to the server it should help your mental model.

Serving Dynamic Webpages with Node.js

I am having a hard time understanding how exactly node.js serves dynamic content.
So let's say we have the following code that renders a home page:
var express = require('express'),
app = express();
app.get('/', function(req,res){
res.render('home.html');
});
However, let's say this home page was supposed to be a user profile in which you are pulling user information from a database, which results in code:
var express = require('express'),
mongoose = require('mongoose'),
app = express();
mongoose.connect('mongodb://localhost/ExampleDB');
app.get('/:id', function(req,res){
User.findOne({_id: req.id}, function (err, user){
var name = user.name;
var profilePic_uri = user.profilePic_uri;
res.render('home.html');
});
So, ideally home.html is just a template page, in which you set maybe the user's profile picture, their name, etc in the route handler. Right, because the idea behind node, is that this app.js should be able to handle pulling the dynamic content from a database at run time. Where I am having trouble is understanding how exactly rendering dynamic pages work with node. The html page is a static page. You can't really render a php or a asp page because, well, that doesn't really make sense does it?
Which leaves me with the question, how is it done?
If you add...
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...after app=express() has been done then it will now default to the Jade rendering engine if you don't use an extension. Then in your router:
app.get('/', function(req,res){
res.render('home', {
var1: 'val1',
var2: 'val2'
});
});
You'd need to add Jade to your project's package.json file in the dependencies:
"jade": "~1.9.1",
...and then "npm install" in your folder to bring that in.
Then you'd need a file named /views/home.jade with the contents:
doctype html
html
body
p Var1 is #{var1}
p Var2 is #{var2}
You should see--when you visit your home page--that the values have been passed to the Jade rendering engine and expanded in place in the template as 'val1' and 'val2', respectively.
In your case the page is static. Here comes in play template engines (view engines), with this you can render the content of the page dynamic.
Some of the template engines that I remember right now are vash (it's like razor syntax from MVC, I love it) and jade. There are more of them.
Note: You can find in the links I provided how to integrate them with express.
What you are actually asking is not, how it works in Node, but how Express renders templates. Once you understand that you're actually using a feature of the express module, you're probably more aware of what you need to search for to get the correct documentation.
In short: Express features a template rendering engine that does the job for you, very much similar to what ASP or PHP do.
To get to know Node, I'd advise to try to build something without all the libraries first, just to get to know the platform, and to understand why it's feasible to use such libraries or frameworks (such as express).