0

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm curious to know why you say "ideally" one should use nginx or similar instead of node for static files.
Removed it, Just so people don't get too curious. :)
0

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.

1 Comment

yes I could do that, but this is just for educational purpose. I want to know how things work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.