How to improve speed of programatically sending images - node.js

I am serving images via express, and substituting generic images when those images don't exist. The HTML which uses those images is generated by EJS looping through an array and creating the img src URLs.
This is a simplified version of my code:
env
people = [
{id: "10937290375", name: "John Smith"},
{id: "73402394793", name: "Paul Jones"}
]
ejs
<% for(var i=0; i < people.length; i++) { %>
<li>
<img src="/image/<%= people[i].id %>" />
<span><%= people[i].name %></span>
</li>
<% } %>
node.js
app.get('/image/:id', function(req, res) {
var filename = `images/${req.params.id}.png`;
res.sendFile(filename, function(err) {
if(err) {
filename = 'blank.png';
res.sendFile(filename);
}
});
});
The problem, is that it is very slow, and syncronous (I guess in part due to the way http works), but how can I speed this up?

Why not use a third party provider as your images repo.
I recommend Cloudinary - they have node js package and very easy integration.

Related

How do i make the ejs variable work that i send from nodejs?

I am tring to get a variable that i send from nodejs to ejs to work. But for some reason it wont, i cant figure out why.
This is the index.js:
var newOne = "Yes"
router.get('/main', ensureAuthenticated, (req, res) =>
res.render('main', {
user: req.user,
newOneInView : newOne
})
)
And this is in the main.ejs file:
<%if (newOneInView == "Yes") { %>
document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
<% } %>
So what i am trying to achieve is that variable will be seen from the nodejs at the main.ejs page but some reason it wont change the image SRC. What am i doing wrong here?
In your template you need to make sure that you place the code for changing the src attribute in a script that is placed after the element (alternatively you can use a listener for the content to be loaded), e.g:
<body>
<img id="avatar" src="/some-other-path"/>
<script>
<% if (newOneInView === "Yes") { %>
document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
<% } %>
</script>
</body>

Client side and Server side rendering of ejs template

I always wanted to learn NodeJS to be able to run the same code on server and client side.
I am using NodeJS with Express and EJS.
So. I have a .ejs page with lot's of HTML, JS, CSS and a small bit with template. For the sake of justice let it be like this:
the_list-->some.ejs
<ul>
<% for(i=0;i>the_list.length;i++) { %>
<li>the_list[i]</li>
<% } %>
</ul>
After some rendering on the server we have a perfect list.
So.
Now I want to rerender it on the client. I made some ajax request and now I have new items in the_list. What is the right way?
As per ejs templates documentation
var template = new EJS({
text: `
<ul>
<% for(i = 0; i < the_list.length; i++) { %>
<li>the_list[i]</li>
<% } %>
</ul>
`
});
var html = template.render({ the_list: data });
document.getElementById('list-wrapper').innerHTML = html;
<div id="output"></div>
<script src="/assets/js/ejs.js"></script>
<script>
let blogPosts = [
{
title: 'Perk is for real!',
body: '...',
author: 'Aaron Larner',
publishedAt: new Date('2016-03-19'),
createdAt: new Date('2016-03-19')
},
{
title: 'Development continues...',
body: '...',
author: 'Aaron Larner',
publishedAt: new Date('2016-03-18'),
createdAt: new Date('2016-03-18')
},
{
title: 'Welcome to Perk!',
body: '...',
author: 'Aaron Larner',
publishedAt: new Date('2016-03-17'),
createdAt: new Date('2016-03-17')
}
];
var html = ejs.render(`<% for(let i = 0; i < posts.length; i++) { %>
<article>
<h2><%= posts[i].title %></h1>
<p><%= posts[i].body %></p>
</article>
<% } %>`, {posts: blogPosts});
// Vanilla JS:
document.getElementById('output').innerHTML = html;
</script>
download ejs.js or ejs.min.js from latest version
Sure, EJS works on the client. You can trivially keep the template in a string variable or apply EJS to user-provided input, but more likely, you'll want to store a template in a script (which can be in an external file) or use fetch to grab your template from another file on demand.
Using a template in a <script> is straightforward:
const people = ["geddy", "neil", "alex"];
const template = document
.querySelector("#template")
.innerText;
document.querySelector("#output")
.innerHTML = ejs.render(template, {people});
<!-- could be an external file -->
<script id="template" type="text/template">
<%= people.join(", "); %>
</script>
<div id="output"></div>
<script src="https://unpkg.com/ejs#3.1.8/ejs.min.js"></script>
For fetch, I'll mock the response so it'll be runnable in a snippet:
// mock fetch for illustrative purposes;
// its response content would be another file
fetch = async url => ({text: async () => '<%= people.join(", "); %>'});
fetch("/your-template")
.then(res => res.text())
.then(template => {
const people = ["geddy", "neil", "alex"];
document.querySelector("#output").innerHTML =
ejs.render(template, {people});
});
<script src="https://unpkg.com/ejs#3.1.8/ejs.min.js"></script>
<div id="output"></div>
If this seems like too much heavy lifting, you can bury the fetch in a helper function, or go a step further and pick an attribute for each URL, then plug everything in with a call to a library function you can abstract away from the main code. A simple example:
// mock fetch for illustrative purposes;
// its response content would be in other files
const responses = {
"/template.ejs": "<%= 42 %>",
"/other-template.ejs": "<%= 43 %>",
};
fetch = async url => ({text: async () => responses[url]});
[...document.querySelectorAll("[data-template]")]
.forEach(e => {
fetch(e.getAttribute("data-template"))
.then(res => res.text())
.then(template => {
e.innerHTML = ejs.render(template);
});
});
<script src="https://unpkg.com/ejs#3.1.8/ejs.min.js"></script>
<div data-template="/template.ejs"></div>
<div data-template="/other-template.ejs"></div>
Either way, keep in mind that JS will run after the static HTML is parsed and the DOM loads. This means the data won't appear all in one fully-formed piece as when using EJS on the server. Network errors are possible.
See also using ejs partials from express client side. If you want to mock the include function, the problem is that the fetch call is asynchronous but the include function isn't. EJS offers an include callback that seems like it offers an opportunity to pull in an external file, but it's purely synchronous and won't await any promises you return. How to work around this best depends on your use case.
This should work, looks like your problem was the relational operator '>' because it will never output something.
<ul>
<% for(var i=0; i<the_list.length; i++) { %>
<li>
<a>
<%= the_list[i]%>
</a>
</li>
<% } %>
</ul>

Conditional operators in ejs

This might sound really easy. There is a very similar
answer but somehow my code is behaving abruptly and driving me crazy. I have spent last 4-5 hours on this. Any help would be great.
I am building a Socket.IO chat app using Node + Express + Passport. I want to compare the userId of the current user with that of other users connected. I want to show him all users except himself to chat with in Socket.IO.
Read comments on code for clarity :
users.js
app.get('/users', function (req, res) {
var connectedUsers = require('../app').chatUsers; // => This is an array of all logged in user and I am getting this all correctly.
if (req.isAuthenticated()) {
res.render('users', {
currentUser: req.user,
users: connectedUsers,
title: 'OnLineUsers'
});
}
});
users.ejs
<h3>CurrentUser : <%- currentUser.id %></h3> // => This Prints like **abcdefg**
<% for(var i = 0;i < users.length ; i++){ %>
<h3>UserID: <%- users[i].id %></h3> // => This also prints the same **abcdefg** if only one user is connected.
<% if( currentUser.id !== users[i].id){ %> // => But this Conditional Operator does not works and show the current user himself.
<ul>
<li>
<h3> <%= users[i].name %></h3>
<a href="/socket" id="chatRoomUrl">
<button type="submit" class="btn-success">Chat</button>
</a>
</li>
</ul>
<% } %>
<% } %>
Thanks in advance. If there is any silly mistake on my part, please excuse me for wasting your time.
Your code is fine. Maybe there is space in two property. Try :
currentUser.id.trim() !== users[i].id.trim()
Change your following line, notice the change:
<h3> <%= users[i].name %></h3>
to this:
<h3> <%- users[i].name %></h3>

MEAN correct way to refactor ejs express code

I've created a website with express and ejs, pulling JSON in from a file in a local file. I'd like to pass the data in from a mongo database and display with an Angular view. I have a good amount of knowledge in express, angular and mongo. Putting it all together and separating the express tasks from the angular tasks has me hung up a bit.
My app is working over in Heroku at http://healingcenter.herokuapp.com/services/ this is the page I'm unclear on how to separate the express and angular tasks.
It is currently set up in express, this was before I researched angular and the MEAN stack. below is the route config.
router.get('/services', function(req, res) {
var myServices = [];
var entireList = [];
entireList = appdata.services;
appdata.services.forEach(function(item) {
myServices = myServices.concat(item.title);
});
res.render('services', {
title: 'Services',
services: myServices,
list: entireList,
page: 'servicesList'
});
});
/* GET services detail page. */
router.get('/services/:servicesid', function(req, res) {
var myServices = [];
var entireList = [];
appdata.services.forEach(function(item){
if (item.shortname == req.params.servicesid){
entireList.push(item);
myServices = myServices.concat(item.title);
}
});
res.render('services', {
title: 'Services',
services: myServices,
list: entireList,
page: 'servicesDetail'
});
});
This is pulling in the same data.json file from the app.js file with this line of code.
app.locals.appdata = require('./data.json');
The page variable is the important part. An if else statement is customizing which data is brought in. That code is here:
<div class="services">
<% list.forEach(function(item){ %>
<article class="service group">
<% if (page!= 'servicesDetail') { %>
<h3><%= item.title %></h3>
<p><%- item.summary %></p>
more
<% }else{ %>
<a class="back" href="/services/#"><i class="fa fa-chevron-circle-left"></i> back</a>
<h3><%= item.title %></h3>
<p><%- item.description %></p>
<% } %>
</article>
<% }); %>
</div>

Cradle / Express / EJS convert html to its entities

I'm using Cradle with Express and EJS on my blog. Maybe i am missing smth but some of them converts html entities to its equivalents.
I have html in doc.quote field and after this piece of code it changes
quotesDb.view('list/by_date', {
'startkey' : {},
'endkey' : null,
'descending' : true
}, function(err, res) {
if (err) {
r.send();
return;
}
r.partial('quotes', {'quotes' : res}, function(err, str) {
console.log(str);
sendResponse('content', str);
});
});
quotes.ejs:
<% for (var i=0; i<quotes.length; i++) { %>
<div>
<%=quotes[i].value.quote%>
</div>
<div class="date">
<%=(new Date(quotes[i].value.ts*1000)).toLocaleDateString()%><% if (quotes[i].value.author) { %>, <%=quotes[i].value.author%><% } %>
</div>
<% } %>
"res" variable is array which has objects with "content" field (which has html). But after rendering "str" has "quotes[i].value.quote" symbols converted to its entities, say <br> to &lt ; br &gt ;
The answer was found here:
http://groups.google.com/group/express-js/browse_thread/thread/f488d19a1604c30e?pli=1
For rendering with escaping:
<%=var%>
For rendering without escaping:
<%-var%>

Resources