Nodejs append backend data to html - node.js

I am using the html as content and sending the mail, but one more requirement is need to get the data from backend and need to append to the html.I am getting error of syntax at the path can anyone help me
client.query(query, function(err, result1) {
var renderTemplate = function('/index2.html', result1.rows) {
fs.readFile('/index2.html', 'utf8', function(err, file){
return ejs.render('/index2.html', result1.rows); }} });

UPDATE: I realize that ejs v1 may not be as popular, so this was edited to work with v2.
This example uses ejs, be sure to install ejs for this example to work.
I didn't write any error handling, be sure to write the error handling if this is for production.
Rendering a template with inserted data:
var fs = require('fs');
var ejs = require('ejs');
var renderTemplate = function(pathToHtmlTemplate, dataToBeInserted) {
// reads your template file to be used in the callback
fs.readFile(pathToHtmlTemplate, 'utf8', function(err, file) {
// returns a rendered html with data to driver code
return ejs.render(pathToHtmlTemplate, dataToBeInserted);
}
}
Your html template should use something like <%= data.name %> :
<ul>
<li><%=data.name%></li>
<li><%=data.email%></li>
</ul>
Further information about the library: https://github.com/mde/ejs

If your HTML file is prepared to have data appended to it then you can use fs.append like this:
fs.appendFile(pathToFile, dataToAppend, function(err) {
if (err) // Handle error
transporter.sendMail({
from : xxxx#gmail.com,
to : xxxx#gmail.com,
subject : 'Invitation',
html : pathToFile
})
})
But if you have closing tags that may cause issues...

You can use some library like nunjucks(https://mozilla.github.io/nunjucks/api.html#renderstring)
var res = nunjucks.render('foo.html', { username: 'James' });
Should give you the html you want.
I didn't try but it should work.

Related

Render HTML with variable data and convert to PDF

I have a html template page that I want to fill in data with via EJS, after which I want to pass this completed page to a PDF creator; the end result being a nice PDF version of my page filled with my data.
For the PDF creator, I'm using the NPM html-pdf do the conversion. Problem is, I don't know of any way I can render the page with my data, save it automatically, then pass the finished page to the PDF creator, since the PDF creator only accepts server paths to saved webpages.
Maybe I'm approaching this the wrong way, but below is what I currently have which admittedly isn't a lot. Any help in the right direction would be appreciated.
var renderPDF = function() {
var pdf = require('html-pdf');
// pulls html page
var html = fs.readFileSync('views/assets/html/render.ejs', 'utf8');
var options = {};
// creates views/test.pdf
pdf.create(html, options).toFile('views/test.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
});
};
// this is how I usually render ejs files with data
response.render('assets/html/render.ejs', {myDataOject});
// start the conversion
renderPDF();
Here is the solution.
We read EJS's template file then compile it to PDF format.
index.js
var fs = require('fs');
var ejs = require('ejs');
var pdf = require('html-pdf')
var compiled = ejs.compile(fs.readFileSync(__dirname + '/template.html', 'utf8'));
var html = compiled({ title : 'EJS', text : 'Hello, World!' });
pdf.create(html).toFile('./result.pdf',() => {
console.log('pdf done')
})
template.html
<html>
<head>
<title><%= title %></title>
</head>
<body>
<p><%= text %></p>
</body>

Uploading a file and sending it to the backend with React and Node

I need to upload a file in react and send it to the Node backend.
Since I never worked with uploading and sending files before, this is a little troubling for me.
So far I found this:
// this creates a React component that can be used in other components or
// used directly on the page with React.renderComponent
var FileForm = React.createClass({
// since we are starting off without any data, there is no initial value
getInitialState: function() {
return {
data_uri: null,
};
},
// prevent form from submitting; we are going to capture the file contents
handleSubmit: function(e) {
e.preventDefault();
},
// when a file is passed to the input field, retrieve the contents as a
// base64-encoded data URI and save it to the component's state
handleFile: function(e) {
var self = this;
var reader = new FileReader();
var file = e.target.files[0];
reader.onload = function(upload) {
self.setState({
data_uri: upload.target.result,
});
}
reader.readAsDataURL(file);
},
// return the structure to display and bind the onChange, onSubmit handlers
render: function() {
// since JSX is case sensitive, be sure to use 'encType'
return (
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" onChange={this.handleFile} />
</form>
);
},
});
Source: https://fitacular.com/blog/react/2014/06/23/react-file-upload-base64/
But now I basically just end up with some sort of string. But I need to send that file via REST to my Express backend, which needs to save that file in CouchDB.
What is the best/easiest way to accomplish that?
If you are using body-parser, know that it handles json and url encoded forms, not multipart data !
You should use an other module.
For more infos, give a look at : File uploading with Express 4.0: req.files undefined

Retrieving HTML from CouchBase into Node.js / Express 4 leaves it unrendered

I'm having a small issue with rendering HTML, stored in CouchBase, fetched by Node.js
In CouchBase I have several small HTML-snippets. They contain text, tags such as <br /> and html entities such as <. They are of course stored as an escaped string in JSON.
So far, so good. However when I pull it out and display on the page, it is rendered "as-is", without being interpreted as HTML.
For example:
[ some content ...]
<p>Lorem is > ipsum<br />And another line</p>
[rest of content ...]
From the controller in Express 4:
var express = require('express');
var router = express.Router();
var couchbase = require('couchbase');
var cluster = new couchbase.Cluster('couchbase://myserver');
var bucket = cluster.openBucket('someBucket', 'somePassword');
var Entities = require('html-entities').XmlEntities;
entities = new Entities();
var utf8 = require('utf8');
/* GET home page. */
router.get('/', function(req, res) {
bucket.get('my:thingie:44', function(err, result) {
if(err) throw err
console.log(result);
var html = utf8.decode(entities.decode(result.value.thingie.html));
// var html = utf8.encode(result.value.thingie.html);
// var html = utf8.decode(result.value.thingie.html);
res.render('index', { title: 'PageTitle', content: html });
});
});
It is then passed to the template (using hogan.js) for rendering.
When looking into this I found that it might have something to do with the encoding of the <'s and <'s that prevent it from being parsed. You can see my converting attempts in the code, where none of the options gave the desired result, i.e. rendering the contents as HTML.
When using utf8.decode(), no difference.
Using utf8.encode(), no difference.
Using entities.decode() it convert < into < as predicted, but it's not rendered even if <div;&gt becomes <div>.
Any ideas?
I found the solution over here: Partials with Node.js + Express + Hogan.js
When putting HTML in a Hogan template, you have to use {{{var}}} instead of {{var}}.
And thus it renders beautifully, as intended :)
Wasn't encoding issues at all ;)

how to retrieve data from mongodb to javascript

I am currently new to nodejs and mongodb, so please forgive me for this newbie type of question.
What I want is to pass data from my mongodb file to my js file which is running my mini-game.
What I am doing right now is using jsp tags to retrieve data from my mongodb (I am following this practice from a project that I have seen, but he is doing this on his html file which is working out well for him. for my case I was just trying my luck)
var win = <%= user.win %>;
var lose = <%= user.lose %>;
var draw = <%= user.draw %>;
How do I retrieve the data I had from my mongodb to javascript?
If you have an Node.JS with Express application, there are many ways to do it. If you're using a template engine, you could render the data as part of the HTML page in a script block (or render it directly as HTML, avoiding script). Or, you might want to use an Ajax style request and send back the data to the client.
app.get('/api/users/:id', function(req, res) {
Users.findOne({ _id : req.params.id }, function(error, user) {
if (error || !user) {
res.send({ error: error });
} else {
res.send(user);
}
});
});
Once you've got that ready, you could use jQuery's ajax function for example to call the web service.
$.ajax({
url: "api/users/" + userId,
}).done(function(user) {
// here you have a complete user object that you can use
});
The code you posted makes me think that you're using a template engine though. I would expect that there is a render method with your template HTML file:
res.render('homepage', user);
Then, in the HTML:
<script>
var win = <%= win %>;
var lose = <%= lose %>;
var draw = <%= draw %>;
</script>
As the user object is the object with current context (as it was passed as the parameter in my example above), you can just directly refer to the properties of the user object directly (just win rather than user.win).

How to compile jade template file to get string?

I have a view logic in my jade template file. How can I pass model in to jade and get html for further sending by email ?
You can try the following:
var jade = require('jade'),
fs = require('fs');
fs.readFile('template.jade', 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
var fn = jade.compile(data);
var html = fn({name:'Oleg'});
console.log(html);
});
Where template.jade is the path to your template. And it look like this:
!!!
html
head
title= 'Hello world'
body
p Hello #{name}!
So you pass your model as input of the fn() function, and the output of it will be the html.
<!DOCTYPE html><html><head><title>Hello world</title></head><body><p>Hello Oleg!</p></body></html>
Also you can catch the string from render callback (express example)
exports.test1 = function(req, res){
res.render('test1', { title: 'test1' }, function(err, body) {
console.log(body);
});
res.send('wooo');
};
test1.jade
div
= title
p hello world!
Opening the template with fs.readFile() is no longer necessary. The Jade API includes the compileFile() method that compiles directly from a file.
var jade = require("jade");
var locals = {name: "Linus"},
render = jade.compileFile('template.jade'),
html = render(locals);
The Jade API also includes the renderFile() method that directly returns an html string from a given file, making it even simpler.
var jade = require("jade");
var locals = {name: "Linus"},
html = jade.renderFile('template.jade', locals);
The answers all work for loading the jade template and compiling it to HTML using locals. However if you are sending HTML emails you need to be aware that most clients strip out all CSS classes. Use Juice (or something like it) to apply all of the CSS classes inline.

Resources