Express, expand variable in static file - javascript

I am using express on a nodejs platform and serve my javascript library files using this directive
app.use('/static', express.static(__dirname + '/static'))
Now I want to be able to write something like that, inside one of these static files
[..] var host = <%= host %> [..]
Is there any possibility to expand variables inside statically served files?

Here's an idea you might want to refine:
var ejs = require('ejs');
//Express.js setup
...
app.use('/public/js/myfile.js', function(req, res){
var f = ejs.compile('var host = <%= hostname %>;');
var fileContent = f({hostname: 'somevalue'});
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Content-Length', fileContent.length);
res.send(fileContent);
});
app.use(express.static(path.join(__dirname, 'public')));
//Routes definition
...
I used ejs since that's what you already use. So the idea is to have a middleware that catches requests to those "dynamic" javascript files, and use the template engine to compile the content.
Note that I use a simple string variable here, but you could read the file from disk and then compile it.
Cheers

You can use loDash's templating with express using lodashinexpress.

Please see my answer here: https://stackoverflow.com/a/19812753/2728686
Using the Jade templating engine you can serve static files and send serverside javascript variables to the static HTML files (or to any jade templates), as such:
Server side (server.js):
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', ensureAuthenticated, function(request, response){
response.render('index', { data: {currentUser: request.user.id} });
});
app.use(express.static(__dirname + '/www'));
views/index.jade:
!!! 5
script(type='text/javascript')
var local_data =!{JSON.stringify(data)}
include ../www/index.html

Related

Node JS - HTML Paths

I recently have the problem that I dont get how the paths for html in node js work. I link my index.html's scripts as normal - relative to the index.html's file (node.js file and index.html are in the same directory "res.sendFile(__dirname + '/index.html');"). But if I open it up in the Browser executed with node js it just stats "cant GET blabla" for the scripts. Instead opening it up by just clicking index.html without node js those paths work! How do I have to write html paths for node js?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
port = Number(process.env.PORT || 3000),
server.listen(port);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Thanks for your time! :)
Look at this:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
You have told Node "When the browser asks for / give it index.html".
What happens when the browser asks for someScript.js?
You haven't told Node what to do then.
(You'll probably want to find a library for serving up static files rather than explicitly handling each one individually).
you should configure express to server static files, for example, put all the static files under a directory called 'public'
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
ExpressJS to Deliver HTML Files
Render HTML file in ExpressJS
You can use
app.use(express.static(path.join(__dirname, "folder-name")));
Usually i put all my static files in a separate folder named "assets"
The I set up a static route as shown below:enter code here
app.use('/assets', express.static('assets'));
When you write:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
It will only serve index.html file, not the other js scripts and stylesheets which you have added in your html.
There are 2 ways to solve that:
For both of them, I would suggest to use 'path' module.
Solution 1:
var path = require('path')
app.get('/path/to/js/foo.js',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/js/foo.js')
})
app.get('/path/to/css/bar.css',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/css/bar.css'))
})
and so on for every .css and.js file you have added in your index.html.
Solution 2:
You can create a public dir in your project's root dir. Inside which all your img, css and js files will be there.
Next,
var path = require('path')
app.use(express.static('public'))
app.get('/',function(req,res){
res.sendFile(path.resolve(__dirname,'/index.html')
})

How do I send HTML in chunks using Node.js and Express?

I want to send the <head> containing stylesheets before processing the rest of the page. In PHP, I could use ob_flush().
I tried doing something like this:
app.set('view engine','ejs');
app.get('*',function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.write('<!doctype...<link rel=stylesheet...');
doDBStuff()
.then(function(data){
res.render('index',{...}); // uses EJS for templating
});
});
However, the res.render() part does not get sent. Is there a built-in way to send chunked data?
One way to do it would be to manually load the EJS files and manually process them. I would also have to manually send the appropriate headers. I prefer a build-in method if it exists.
Here's a simple PoC that does what you want:
var express = require('express');
var app = express();
var server = app.listen(3000);
app.set('views', 'views');
app.set('view engine', 'ejs');
app.get('/', function (req, res, next) {
res.write('<!-- prefix -->');
setTimeout(function() {
res.render('index', { ... }, function(err, html) {
// TODO: handle errors
res.end(html);
});
}, 1000);
});
Note that it uses the "callback variant" of res.render(), which can be used to just render a template without sending back a response (if you don't do it this way, res.render() will generate an error). Alternatively, you can use app.render() which does the same.

How to set path to partials in Node.js with Express, Handlebars and Conslidate

I have a working Node.js site, using Express.js, Handlebars.js and Consolidate.js. I want to use partials for common parts of my templates, but can't work out how to make them work for pages at different URLs.
My /views/ directory contains this:
_footer.html
_header.html
article.html
index.html
The relevant parts of my Node app looks something like:
var express = require('express'),
consolidate = require('consolidate'),
handlebars = require('handlebars'),
path = require('path');
var app = express();
app.engine('html', consolidate.handlebars);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, '/views'));
var partials = {header: '_header', footer: '_footer'};
app.get('/', function(req, res) {
res.render('index', {partials: partials});
};
app.get(/^\/([\w-]+)\/$/, function(req, res) {
res.render('article', {partials: partials});
};
And in my index.html and article.html Handlebars templates I have something like:
{{> header}}
<!-- page content here -->
{{> footer }}
I should be able to access both / (when index.html is rendered) and /foo/ (when article.html is rendered). But it only works for whichever I try to access first after starting the Node server. When I then navigate to the other path, I get errors like:
Error: ENOENT, no such file or directory '/Users/phil/Projects/projectname/views/<!DOCTYPE html>...
with the rest of the _header.html partial following.
I assume I need to somehow set the path to my partials to be absolute somehow, but I can't see how to do that.
For consolidate check that : https://github.com/tj/consolidate.js/issues/18
I would recommend to switch to something a bit more specific like that https://github.com/donpark/hbs it will be simpler.
I had the same exact issue. It seems that consolidate is reusing the "partials" object that you pass, replacing the values with the file content (yuck!).
A workaround is to create a new "partials" object every time. If you don't want to rewrite the whole object every time, you can use a function returning the object literal.
In your case something like the following should work:
var express = require('express'),
consolidate = require('consolidate'),
handlebars = require('handlebars'),
path = require('path');
var app = express();
app.engine('html', consolidate.handlebars);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, '/views'));
var partials = function() {
return {header: '_header', footer: '_footer'};
}
app.get('/', function(req, res) {
res.render('index', {partials: partials()});
};
app.get(/^\/([\w-]+)\/$/, function(req, res) {
res.render('article', {partials: partials()});
};
Not really elegant, but I don't think there is really a way to keep it simpler.

Render raw HTML

I want to render raw .html pages using Express 3 as follows:
server.get('/', function(req, res) {
res.render('login.html');
}
This is how I have configured the server to render raw HTML pages (inspired from this outdated question):
server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(str, options) {
return function(locals) {
return str;
};
});
Unfortunately, with this configuration the page hangs and is never rendered properly. What have I done wrong? How can I render raw HTLM using Express 3 without fancy rendering engines such as Jade and EJS?
What I think you are trying to say is:
How can I serve static html files, right?
Let's get down to it.
First, some code from my own project:
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
What this means that there is a folder named public inside my app folder. All my static content such as css, js and even html pages lie here.
To actually send static html pages, just add this in your app file
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/layout.html');
});
So if you have a domain called xyz.com; whenever someone goes there, they will be served layout.html in their browsers.
Edit
If you are using express 4, things are a bit different.
The routes and middleware are executed exactly in the same order they are placed.
One good technique is the place the static file serving code right after all the standard routes.
Like this :
// All standard routes are above here
app.post('/posts', handler.POST.getPosts);
// Serve static files
app.use(express.static('./public'));
This is very important as it potentially removes a bottleneck in your code. Take a look at this stackoverflow answer(the first one where he talks about optimization)
The other major change for express 4.0 is that you don't need to use app.configure()
If you don't actually need to inject data into templates, the simplest solution in express is to use the static file server (express.static()).
However, if you still want to wire up the routes to the pages manually (eg your example mapping '/' to 'login.html'), you might try res.sendFile() to send your html docs over:
http://expressjs.com/api.html#res.sendfile
Have you tried using the fs module?
server.get('/', function(req, res) {
fs.readFile('index.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
as the document says : 'Express expects: (path, options, callback)' format function in app.engin(...).
so you can write your code like below(for simplicity, but it work):
server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(path, options, cb) {
fs.readFile(path, 'utf-8', cb);
});
of course just like 2# & 3# said, you should use express.static() for static file transfer; and the code above not suit for production
First, the mistake you did was trying to use the express 2.x code snippet to render raw HTML in express 3.0. Beginning express 3.0, just the filepath will be passed to view engine instead of file content.
Coming to solution,
create a simple view engine
var fs = require('fs');
function rawHtmlViewEngine(filename, options, callback) {
fs.readFile(filename, 'utf8', function(err, str){
if(err) return callback(err);
/*
* if required, you could write your own
* custom view file processing logic here
*/
callback(null, str);
});
}
use it like this
server.engine('html', rawHtmlViewEngine)
server.set('views', './folder');
server.set('view engine', 'html');
Reference
Official express 2.x to 3.x migration guide
See 'Template engine integration' section in this url
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
After a fresh install of the latest version of Express
express the_app_name
Creates a skeleton directory that includes app.js.
There is a line in app.js that reads:
app.use(express.static(path.join(__dirname, 'public')));
So a folder named public is where the magic happens...
Routing is then done by a function modeled this way:
app.get('/', function(req,res) {
res.sendfile('public/name_of_static_file.extension');
});
*Example:*
An index.html inside the public folder is served when invoked by the line:
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
As far as assets go:
Make sure the css and javascript files are called from the folder relative to the public folder.
A vanilla Express install will have stylesheets, javascripts, and images for starting folders. So make sure the scripts and css sheets have the correct paths in index.html:
Examples:
<link href="stylesheets/bootstrap.css" rel="stylesheet">
or
<script src="javascripts/jquery.js"></script>
You can render .html pages in express using following code:-
var app = express();
app.engine('html', ejs.__express);
And while rendering, you can use following code:-
response.render('templates.html',{title:"my home page"});
I wanted to do this because I'm creating a boilerplate NodeJS server that I don't want tied to a view engine. For this purpose it's useful to have a placeholder rendering engine which simply returns the (html) file content.
Here's what I came up with:
//htmlrenderer.js
'use strict';
var fs = require('fs'); // for reading files from the file system
exports.renderHtml = function (filePath, options, callback) { // define the template engine
fs.readFile(filePath, function (err, content) {
if (err) return callback(new Error(err));
var rendered = content.toString();
// Do any processing here...
return callback(null, rendered);
});
};
To use it:
app.engine('html', htmlRenderer.renderHtml);
app.set('view engine', 'html');
Source: http://expressjs.com/en/advanced/developing-template-engines.html
Comments and constructive feedback are welcome!
After years a new answer is here.
Actually this approach like skypecakess answer;
var fs = require('fs');
app.get('/', function(req, res, next) {
var html = fs.readFileSync('./html/login.html', 'utf8')
res.send(html)
})
That's all...
Also if EJS or Jade will be used the below code could be used:
var fs = require('fs');
app.get('/', function(req, res, next) {
var html = fs.readFileSync('./html/login.html', 'utf8')
res.render('login', { html: html })
})
And views/login.ejs file contains only the following code:
<%- locals.html %>
app.get('/', function(req, res) {
returnHtml(res, 'index');
});
function returnHtml(res, name) {
res.sendFile(__dirname + '/' + name + '.html');
}
And put your index.html to your root page, of course you could create a /views folder for example and extend returnHtml() function.
You can send file using res.sendFile().
You can keep all html files in views folder and can set path to it in options variable.
app.get('/', (req, res)=>{
var options = { root: __dirname + '/../views/' };
var fileName = 'index.html';
res.sendFile(fileName, options);
});

rendering jade files in expressjs

I have a basic expressjs app (using jade), but I am having trouble rendering basic Jade files. When I get a request, i parse the url for the pathname and use the handle object to route the request as follows:
index.js
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/'] = requestHandlers.start;
handle['/download'] = requestHandlers.download
requestHandlers.js
function start(res) {
console.log("request handler for start called");
res.render('home', {title: 'express'});
}
function download(res) {
res.render('download', {title: 'download'})
res.end();
}
exports.start = start;
exports.download = download;
home.jade
h1= title
p Welcome to #{title}
I am using Jade as my templating engine, and have configured the server in a seperate server.js file. When i request either of the pages, the title displays correctly on my browser tab, but the page doesn't display, it just keeps loading. Weirdly, when I cancel the request the page displays. It's as if everything works but nothing tells the process to end?
I am relatively new to node so excuse my naiveté on any of the above. Let me know if there are any questions I can clear up.
I'm not 100% positive why your code isn't killing the TCP connection as needed to prevent your browser from timing out, but I can provide a solution that is friendly towards Express conventions that should solve your issues and maintain code readability, maintainability, and separation.
./app.js (your main server script)
var express = require('express'),
app = express.createServer(),
routes = require('./routes');
app.configure(function () {
// Render .jade files found in the ./views folder
// I believe you are already doing this
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// Use the built-in Express router
// This kills the "handle" method you had implemented
app.use(app.router);
// Client-side assets will be served from a separate ./public folder
// i.e. http://yourhost.com/js/main.js will link to ./public/js/main.js
app.use(express.static(__dirname + '/public'));
});
// Initialize routes
routes.init(app);
./routes/index.js
exports.init = function (app) {
app.get('/', function (req, res) {
console.log("request handler for start called");
// Render __dirname/views/home.jade
res.render('home', {title: 'express'});
});
app.get('/download', function (req, res) {
// Render __dirname/views/download.jade
res.render('download', {title: 'download'})
});
});
The above prevents you from needing to parse the URL parameters by yourself. Also you can define more readable and powerful request handlers (i.e. app.post for POST methods). You are now enabled to more easily tie in things like the Express-Resource module if you decide to build a REST API.
If you need more powerful mappings you can use regular expressions in the first parameter of app.[get/post/put/del] to filter for specific paths instead.

Categories