I have following setup in cloud9 IDE.
Project root folder
- Hello.html – contains simple html tags (+image tag) Preview displays the image
- HelloHtml.js – node js file that reads html file and writes to the client (response). .
- Penguins.jpg – image file in the same folder.
When I run the service and hit the URL in browser, HTML gets rendered with “Hello World!” being displayed as . But the image is not getting rendered. What should be the src=”” attribute in the img tag.
What should be the path for the image file? Thank you.
HelloHtml.js
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./Hello.html', function(err, data){
if(err) throw err;
response.end(data);
});
}).listen(process.env.PORT);
console.log('Hello World HTML Service has started.');
Hello.html
<html>
<head>
<title>Node JS</title>
</head>
<body>
<h2>Hello world!</h2>
<img src="Penguins.jpg" />
</body>
</html>
You are not handling static files serving anywhere in your code, you are just serving the file ‘hello.html’ no matter what:
Either make a routing scheme, based on the request url or use some static file server from here:
https://github.com/joyent/node/wiki/modules#wiki-web-frameworks-static
I suggest you take a look at Express, it has that and route handling also: expressjs.com