Node.JS images not displaying to clients - javascript

I have server.js and client.html.
Server.js is running on nodejs and is simply:
var http = require('http'), fs = require('fs');
var app = http.createServer(function(request, response) {
fs.readFile("client.html", 'utf-8', function(error, data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
});
}).listen(80);
and then I have client.html which is also very simply just
<img src="/public/images/avatar.gif">
Which just displays as though the image is not valid, I have checked the the director over and over and it is fine, why would it be doing this? I thought it might be because of the headers but text/html should surely display images?
Regards
Matt

It's not displaying the image because for every request (including the image request) it's returning the contents of clients.html.
If you want a static file server, i suggest looking at connect: http://www.senchalabs.org/connect/ or for something simpler, have a look at this: https://gist.github.com/rpflorence/701407

Related

Node.js page not loading when refreshed

I want to create a simple Node.js server and send data with pipe() method. But I have an issue.
The page loads when server started the first time, but when I refresh the page, it becomes blank. I mean the data is not loaded. Why does it happen?
var http = require('http'),
fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
myReadStream.pipe(res);
}).listen(3300);
This would work if you change it to:
http.createServer(function (req, res) {
var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
res.writeHead(200, {'Content-Type': 'text/plain'});
myReadStream.pipe(res);
}).listen(3300);
That's because the stream once read is not rewinded automatically (in fact it cannot be).
But it's not the most flexible way to serve static content.
See this answer for five examples of serving static files with and without Express, from using high-level frameworks to very low level manual reinventing the wheel kind of implementation.
How to serve an image using nodejs

node.js won't read and display html file

I'm trying to read and display a basic html file with node.js, but i get no luck, since anything i do it returns the same error.
Here's the code
var http = require('http');
var fs = require('fs');
var url = require('url');
var port = 3000;
fs.readFile('./funckcionalnosti.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
}).listen(3000);
});
The error i get
I've read some things about node not dealing with temporary files, or that my file may not be within current script...i already tried moving files, tried _dirname and copying the entire path name, but it still won't work.
Any help please?

Image not display serving image using GridFS in Node.js

I am taking in a png file from AFNetworking saving it to GridFS and then I would like to be able to retrive it at some point. Out of curiousity I logged the image before it entered GridFS and it looks like..
<89504e47 0d0a1a0a 0000000d 49484452 00000074 0000008c 08020000 0022391a ...>
I save this in a buffer and then store it into GridFS.
When I am retrieving it via a GET request I log it again before sending it out and it appears to be in the same format.
Then I attempt to do this
res.writeHead(200, {'Content-Type': 'image/png' });
gs.createReadStream(image).pipe(res); //using GridJS this it the syntax to read
When viewing this in a browser it just appears like an empty or broken image link. If I inspect the page source it appears to be just
If I never set the headers it just appears as hundreds of lines of
<89504e47 0d0a1a0a 0000000d 49484452 00000074 0000008c 08020000 0022391a ...>
I feel like I am not converting a buffer right or something.
var http = require('http'),
MongoDB = require("mongodb"),
MongoClient = require("mongodb").MongoClient,
GridStore = require("mongodb").GridStore;
http.createServer(function (req, res) {
console.log("Serving request for file: " + req.url);
MongoClient.connect("mongodb://localhost:27017/test", {}, function(err, db) {
gridStore = new GridStore(db, req.url, "r");
gridStore.open(function(err, gs) {
if (err) {
console.log("error in open: " + err);
return;
}
res.writeHead(200, {'Content-Type': 'image/png'});
var s = gs.stream(true);
s.pipe(res);
});
});
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
I can successfully run server and serve the png files successfully to the browser using the code pasted above. However since, you are saying that raw contents of the source does appear on client side when you do a "see source". I would suggest trying the code I wrote and see if that has the same issues.

Serve jpeg file in node without framework

I am trying to learn the ins and outs of node. I know you can serve a file with a framework but I am trying to do it manually. I have a jpeg file in './public/logo.jpg'. When I send the request through localhost:8080 I don't get the image, just a blank screen with a generic image placeholder. What am I doing wrong? Thanks!
var http=require('http');
var url=require('url');
var fs=require('fs');
// creates a new httpServer instance
http.createServer(function (req, res) {
// this is the callback, or request handler for the httpServer
log('in server callback')
res.ins=res.write;
var parse=url.parse(req.url,true);
var path0=parse.pathname;
console.log(path0)
// respond to the browser, write some headers so the
// browser knows what type of content we are sending
var serveFile=function(){
var path='./public'+path0
fs.exists(path,function(e){
if(e){
log('serving file')
log(path)
fs.readFile(path,'binary',function(err,data){
if(data){
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.ins(data)
res.end()
}
})
}
else{
log('no file to serve')
log(path)
servePage()
}
})
}
serveFile()
}).listen(8080); // the server will listen on port 8080
Simply change the following two lines in your readFile callback :
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.write(data, 'binary');
Use response.write to send data to the client and set encoding to binary. (Default is utf-8)

Setting a document root to your Node.js http server?

I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
Use Express or Connect. Examples: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html
For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.
You may add some code to your function like:
var http = require('http'),
io = require('socket.io'),
fs = require('fs'),
server = http.createServer(function(req, res){
// find static image file
if (/\.gif$/.test(req.pathname)) {
fs.read(req.pathname, function(err, data) {
res.writeHead(200, { 'Content-Type': 'image/gif' });
res.end(data);
});
}
else {
// write your div
}
});
server.listen(8080);
I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.

Categories

Resources