I am building my first Node.js MVC app (native node, not using Express) and having trouble displaying images from my html files via relative their paths.
I'll spare you my server.js and router.js code, but here is my controller code which is basically how Im loading my views:
var fs = require("fs");
var controller = require("controller");
var load_view = 'view_home';
var context = { foo : 'bar' };
controller.load_view(res, req, fs, load_view, context);
this gets passed to...
var url = require('url');
var Handlebars = require('handlebars');
function load_view(res, req, fs, view, context, session){
// Files to be loaded, in order
var files = [
'view/elements/head.html',
'view/elements/header.html',
'view/' + view +'.html',
'view/elements/footer.html'
];
// Start read requests, each with a callback that has an extra
// argument bound to it so it will be unshifted onto the callback's
// parameter list
for(var i=0; i<files.length; ++i)
fs.readFile(files[i], handler.bind(null, i));
var count = 0;
function handler(index, err, content) {
// Make sure we don't send more than one response on error
if(count < 0) return;
if(err) {
count = -1;
console.log('Error for file: ' + files[index]);
console.log(err);
res.writeHead(500);
return res.end();
}
// Reuse our `files` array by simply replacing filenames with
// their respective content
files[index] = content;
// Check if we've read all the files and write them in order if
// we are finished
if(++count===files.length) {
res.writeHead(200, { 'Content-Type': 'text/html' });
for(var i = 0; i < files.length; ++i) {
var source = files[i].toString('utf8');
// Handlebars
var template = Handlebars.compile(source);
var html = template(context);
res.write(html); /* WRITE THE VIEW (FINALLY) */
}
res.end();
}
} // handler()
} // load()
Finally, here is my html with tag and relative path in the src attribute:
<div class="help">
<img src="../public/img/test.jpg" />
</div>
My file system as it relates to the above is as follows:
I am certain the relative path is correct but have tried all combinations of a relative path and even an absolute path. Still, no image is displayed.
Coming from a LAMP background, accessing images in the file tree is trivial but I realize the server is set up much differently here (since I was the one who set it up).
I access other files (like stylesheets) in the filesystem by creating a separate controller to load those files explicitly and access that controller using a URI. But this approach in impractical for an indeterminate number of images.
How do I access & display my images in the filesystem with Node.js?