Dust.js load template from filesystem in Node.js - node.js

I'm trying to load template from file system using node.js and can't find the way.
So far I have:
exports.index = function(req, res){
var compiled = dust.compile("Hello {name}!", "intro");
dust.loadSource(compiled);
dust.render("intro", {name: "Fred"}, function(err, out) {
res.write(out);
res.close();
});
};
Is there is a way to replace: "Hello {name}!" with file name? Should it be HTML or JS file?
Also if that's not really great way on rendering templates let me know, I'm new to Node.js trying to pick up best practices.

fs.readFile(dustFile, function (err, file) {
var name = fileName.split(".")[0]
var fn = dust.compileFn(file.toString(), name)
fn({ name: "fred" }, function (err, out) {
res.end(out)
})
})

This should help you. dust fs.
This is a simplified interface to use templates from filesystem with {dust} using Node.js.
https://github.com/jheusala/dustfs

Related

Nodejs append backend data to html

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.

ExpressJS & Mongoose REST API structure: best practices?

I'm building a REST API with the use of NodeJS (Mongoose & ExpressJS). I think I have a pretty good basic structure at the moment, but I'm wondering what the best practices are for this kind of project.
In this basic version, everything passes through the app.js file. Every HTTP method is then passed to the resource that has been requested. This allows me to dynamically add resources to the API and every request will be passed along accordingly. To illustrate:
// app.js
var express = require('express');
var mongoose = require('mongoose');
var app = express();
app.use(express.bodyParser());
mongoose.connect('mongodb://localhost/kittens');
var db = mongoose.connection;
var resources = [
'kitten'
];
var repositories = {};
for (var i = 0; i < resources.length; i++) {
var resource = resources[i];
repositories[resource] = require('./api/' + resource);
}
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
console.log('Successfully connected to MongoDB.');
app.get('/:resource', function (req, res) {
res.type('application/json');
repositories[req.params.resource].findAll(res);
});
app.get('/:resource/:id', function (req, res) {
res.type('application/json');
repositories[req.params.resource].findOne(req, res);
});
app.listen(process.env.PORT || 4730);
});
-
// api/kitten.js
var mongoose = require('mongoose');
var kittenSchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittenSchema);
exports.findAll = function (res) {
Kitten.find(function (err, kittens) {
if (err) {
}
res.json(kittens);
});
};
exports.findOne = function (req, res) {
Kitten.findOne({ _id: req.params.id}, function (err, kitten) {
if (err) {
}
res.json(kitten);
});
};
Obviously, only a couple of methods have been implemented so far. What do you guys think of this approach? Anything I could improve on?
Also, a small side question: I have to require mongoose in every API resource file (like in api\kitten.js, is there a way to just globally require it in the app.js file or something?
Any input is greatly appreciated!
Well, you can separate out your routes, db models and templates in different files.
Have a directory structure something like this,
| your_app
| -- routes
| -- models
| -- templates
| -- static
| -- css
| -- js
| -- images
| -- config.js
| -- app.js
| -- url.js
For each Mongoose model have a separate file placed in your ./models
In templates directory place your jade files. (Assuming you are using jade as your template engine). Though it seems like you are only serving JSON, not HTML. Consider using Jade if you want to render HTML. (Here are few other template engines you can consider going with)
./static directory for static JS, CSS and XML files etc.
Things like db connections or 3rd party API keys and stuff can be put in config.js
In url.js have a procedure which take express app object as argument and extend upon app.get and app.post there in single place.
P.S. This is the approach I go with for a basic web app in express. I am in no way saying this the best way to follow, but it helps me maintain my code.
There is no right way, but I did create a seed application for my personal directory structure to help my roommate with this.
You can clone it: git clone https://github.com/hboylan/express-mongoose-api-seed.git
Or with npm: npm install express-mongoose-api-seed
As codemonger5 said there is no right way of organising directory structure.
However, you can use this boilerplate application for creating REST APIs using Express and mongoose using ES6. We use the same directory structure in our production API services.
git clone https://github.com/KunalKapadia/express-mongoose-es6-rest-api
cd express-mongoose-es6-rest-api
npm install
npm start

Examples and documentation for couchnode

I am trying to integrate couchbase into my NodeJS application with couchnode module. Looks like it lacks of documentation. I see a lot of methods with parameters there in the source code but I can't find much information about how they work. Could you please share me with some, may be examples of code? Or should I read about these methods from other languages' documentation as there are chances they are the same?
To make development easier, I wrote a little helper (lib/couchbase.js):
var cb = require('couchbase'),
config;
if(process.env.NODE_ENV === 'production') {
config = require('../lib/config');
} else {
config = require('../lib/localconfig');
}
module.exports = function(bucket, callback) {
config.couchbase.bucket = bucket;
cb.connect(config.couchbase, callback);
};
Here's some example code for a view and async/each get operation. Instead of 'default' you can use different buckets.
var couchbase = require('../lib/couchbase');
couchbase('default', function(error, cb) {
cb.view('doc', 'view', {
stale: false
}, function(error, docs) {
async.each(docs, function(doc, fn) {
cb.get(doc.id, function(error, info) {
// do something
fn();
}
}, function(errors) {
// do something
});
});
});
I adapted an AngularJS and Node.js web application that another developer wrote for querying and editing Microsoft Azure DocumentDB documents to let it work with Couchbase:
https://github.com/rrutt/cb-bread
Here is the specific Node.js module that performs all the calls to the Couchbase Node SDK version 2.0.x:
https://github.com/rrutt/cb-bread/blob/dev/api/lib/couchbaseWrapper.js
Hopefully this provides some help in understanding how to configure arguments for many of the Couchbase API methods.

Get compiled jade template inside view?

I have a "partial" template that I want to use both client-side and server-side.
Is there some method or filter or something that's very similar to include except that instead of executing the template immediately, it returns a client-compiled function which I could then assign to a JS variable and use throughout my script?
At present, I'm doing this:
exports.list = function(req, res){
res.render('file/list', {
...
fileItemTemplate: jade.compile(fs.readFileSync(path.join(req.app.get('views'),'file','file-item.jade')), {client: true})
});
};
And then in my template I have:
ul#folder-list.thumbnails
each file in files
include file-item
...
script(type='text/javascript')
var fileItemTemplate = !{fileItemTemplate};
And in this way I can render some items to HTML on page-load, and then add some more in later by rendering the partial as data comes in.
This works, but it doesn't feel very DRY because I have to read in the file, and deal with filepaths and stuff in the route, and then essentially redeclare the exact same variable client-side.
Is there a nice way of doing this?
Something like this would be ideal:
script(type='text/javascript')
var fileItemTemplate = !{compile file-item};
A possible solution could be JadeAsset. See also the discussion here.
You can hook assets into Express:
assets.on('complete', function() {
var app = express.createServer();
app.configure(function() {
app.use(assets); // that's all you need to do
});
app.listen(8000);
});
To create your Jade assets:
var assets = new AssetRack([
new rack.JadeAsset({
url: '/templates.js',
dirname: __dirname + '/templates'
})
]);

Connect and Express utils

I'm new in the world of Node.js
According to this topic: What is Node.js' Connect, Express and “middleware”?
I learned that Connect was part of Express
I dug a little in the code, and I found two very interesting files :
./myProject/node_modules/express/lib/utils.js
and better :
./myProject/node_modules/express/node_modules/connect/lib/utils.js
These two files are full of useful functions and I was wondering how to invoke them correctly.
As far, in the ./myProject/app.js, that's what I do:
var express = require('express')
, resource = require('express-resource')
, mongoose = require('mongoose')
, expresstUtils =
require('./node_modules/express/lib/utils.js');
, connectUtils =
require('./node_modules/express/node_modules/connect/lib/utils.js');
But I found it a little clumsy, and what about my others files?
e.g., here is one of my routes:
myResources = app.resource(
'myresources',
require('./routes/myresources.js'));
and here is the content of myresources.js:
exports.index = function(req, res)
{
res.render('./myresources.jade', { title: 'My Resources' });
};
exports.show = function(req, res)
{
fonction resourceIsWellFormatted(param)
{
// Here is some code to determine whether the resource requested
// match with the required format or not
// return true if the format is ok
// return false if not
}
if (resourceIsWellFormatted(req.params['myresources']))
{
// render the resource
}
else
{
res.send(400); // HEY! what about the nice Connect.badRequest in its utils.js?
}
};
As you can see in the comment after the res.send(400), I ask myself if it is possible to use the badRequest function which is in the utils.js file of the Connect module.
What about the nice md5 function in the same file?
Do I have to place this hugly call at the start of my myresources.js to use them?:
var connectUtils =
require('../node_modules/express/node_modules/connect/lib/utils.js');
or, is there a more elegant solution (even for the app.js)?
Thank you in advance for your help!
the only more elegant way i came up with is (assuming express is inside your root "node_modules" folder):
require("express/node_modules/connect/lib/utils");
the node installation is on windows, node version 0.8.2
and a bit of extra information:
this way you don't need to know where you are in the path and be forced to use relative paths (./ or ../), this can be done on any file nesting level.
i put all my custom modules inside the root "node_modules" folder (i named my folder "custom_modules") and call them this way at any level of nesting:
require("custom_modules/mymodule/something")
If you want to access connect directly, I suggest you install connect as a dependency of your project, along with express. Then you can var utils = require('connect').utils.

Resources