Thursday, 15 May 2014

javascript - serving image using nodejs -



javascript - serving image using nodejs -

i have image pic.jpeg have display on browser.here snippet of code 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 () { // pipes read stream response object (which goes client) util.pump(stream, res, function(error) { //only called when res closed or error occurs console.log("error:"); res.end(); return; }); });

the above code works of time , images displays should, @ times image missing.

you should not serving static files through node.js. should consider using nginx or similar web server same.

alternatively, can utilize connect module serve static files

var server = connect() .use('/static', connect.static(__dirname + '/static')) .use(router) .listen(port);

make new directory named static , set files in it, able access them /static/images/testimage.jpg

javascript node.js http webserver

No comments:

Post a Comment