javascript - Where to put the image file in node.js? -
i have following directory structure in linux 3 files in it:
/home/nikhil/test_img/
- server.js
- page.html
- pic.jpg
this simple node.js hello world setup without using express or other library
code server.js
var http = require("http"), fs = require('fs'); var path = require('path'); var root = path.dirname(require.main.filename); var filepath = path.join(root + '/page.html'); var port = 8889; function onrequest(request, response) { fs.readfile(filepath, function (err, html) { if (err) { throw err; } response.writehead(200, {'content-type': 'text/html'}); response.write(html); response.end(); }); } http.createserver(onrequest).listen(port, function () { console.log("server has started @ port " + port); });
this creates server displays page.html on request localhost:8889
code page.html
<html> <head><title>page</title></head> <body> <h1> hello world </h1> <img src="pic.jpg" alt="image"> </body> </html>
this simple webpage hello world heading , image.
now, error image not displayed when page loaded when hit localhost:8889 on browser. but, image displayed when open webpage through browser (not via node).
i have tried changing src to
- "/home/nikhil/test_img/page.html"
- "file:///home/nikhil/test_img/page.html"
- "localhost:8889/page.html" but, none of these work
also, tried printing location in javascript using <script>alert(document.location.pathname);</script>
the path printed was
/
whereas, when ran page directly in browser (without node), was
/home/nikhil/test_img/page.html
where need put image file work?
your code says each request should serve file corresponds filepath
i.e. html file page.html
. fine page request itself, img
tag in html page creates separate request image pic.jpg
should exist in same path page. instead of serving img file, means request handler return header content-type: image/jpg
, request handler again responds html page's contents , header content-type:text/html
.
you need differentiate serve, based on being requested.
Comments
Post a Comment