Ryan Williams
Ryan Williams

Reputation: 663

Node js displaying images from server

I am trying to display an image on a basic web page on a localhost w/ port 5000 here is main.js

var http = require('http');

var domain = require('domain');

var root = require('./root');
var image = require('./image');



function replyError(res) {

  try {

    res.writeHead(500);

    res.end('Server error.');

  } catch (err) {

    console.error('Error sending response with code 500.');

  }

};



function replyNotFound(res) {

  res.writeHead(404);

  res.end('not found');

}



function handleRequest(req, res) {

  console.log('Handling request for ' + req.url);

  if (req.url === '/') {

    root.handle(req, res);

  } else if (req.url === '/image.png'){

    image.handle(req, res);

  } else {

    replyNotFound(res);

  }

}



var server = http.createServer();



server.on('request', function(req, res) {

  var d = domain.create();

  d.on('error', function(err) {

    console.error(req.url, err.message);

    replyError(res);

  });

  d.run(function() { handleRequest(req, res); });

});



function CallbackToInit(){

  server.listen(5000);
};
root.init(CallbackToInit);

Using callbacks I want the server to start listening(5000) only after the init function of the following code runs

var http = require('http');

var body;

exports.handle = function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'image/png'
  });
  res.end(body);
};

exports.init = function(cb) {
  require('fs').readFile('image.png', function(err, data) {
    if (err) throw err;
    body = data;
    cb();
  });
}

It's an assignment I can't use express

I am trying to get image.png to be displayed, I think body = data doesn't work because it can't hold an image like a string? I don't want to put any HTML into my js file.

Upvotes: 0

Views: 4122

Answers (2)

Charlie G
Charlie G

Reputation: 824

Take a look at the node.js example for a simple http server or a tutorial/example, such as this, for serving static files through a simple server.

Upvotes: 1

Steve Jansen
Steve Jansen

Reputation: 9494

Don't roll your own app server. Use one of the great web app frameworks like express or connect.

var express = require('express');
var app = express();

app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 5000);

Trust me, this is better.

Upvotes: 1

Related Questions