I have a image pic.jpeg which I have to display on browser.Here is snippet of code I have written.
var mimeTypes = {
'.js' : 'text/javascript',
'.css' : 'text/css',
'.gif' : 'image/gif',
'.jpeg': 'image/jpeg',
'.html': 'text/html'
};
contenttype = mimeTypes[path.extname(req.url)];
pathname = "." + req.url;
var stream = fs.createReadStream(pathname);
stream.on('error', function(error) {
res.writeHead(500);
res.end();
return;
});
res.setHeader('Content-Type', contenttype);
res.writeHead(200);
stream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
util.pump(stream, res, function(error) {
//Only called when the res is closed or an error occurs
console.log("Error:");
res.end();
return;
});
});
The above code works most of the time and the images displays like it should, but at times the image is missing.
You should not be serving static files through node.js. You should consider using Nginx or similar web server for the same.
Alternatively, you can use connect module to serve static files
var server = connect()
.use('/static', connect.static(__dirname + '/static'))
.use(router)
.listen(port);
Make a new directory named static and put all files in it, so you will be able to access them by /static/images/testimage.jpg
Rather than implementing static file serving yourself, why not use a library like Express? You can see that being used here: Express Static nodejs or see the API here: http://expressjs.com/api.html (search for "static"). It'll be a lot less code, and reliable.