Node.js server don't show image - javascript

I am with a problem over here, I am using node.js framework to handle the requests to my index.html.
The index.html file has some images, but its not appearing for my users!
I am reading both files, index.html and the .png .
Can you guys help me?
Here is my server.js:
var app = require('http').createServer(handler)
var io = require('socket.io').listen(app)
var fs = require('fs')
app.listen(4000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
return res.end('Error loading index.html');
}
res.end(data);
});
fs.readFile(__dirname + '/blackq.png', function (err, data) {
if (err) {
return res.end('Error loading index.html');
}
res.end(data);
});
}
THanks alot in advance!

A quick solution just for proof of concept could go like this:
In your html file, make sure you have the img tab done right.
<img src="/your_image.jpg" alt="your_image" style="width:304px;height:228px;">
In your node.js server file, adding
if (req.url == "/index.html") {
//res.end your html file
return;
}
//to display image
if (req.url == "/your_image.jpg") {
var img = fs.readFileSync('./your_image.jpg');
res.writeHead(200, {'Content-Type': 'image/jpg' });
res.end(img, 'binary');
return;
}

Related

Serve static files for an URL with dynamic params in node js without any library or framework

I have a little problem here.
I want to serve one static file for "/user/:id" URL with a simple node server.
How is this possible?
Here is my request in client side:
document.location.href = `http://localhost:8080/user/${x}`;
And this is my request handler:
var routeHandler;
if (req.method === 'GET') {
switch (req.url) {
case '/user/:id':
routeHandler = userProvider;
break;
}
}
function userProvider(req, res) {
req.url = 'index.html';
staticFileHandler(req, res);
}
function staticFileHandler(req, res) {
fs.readFile('client/' + req.url, function (err, data) {
if (err) {
res.writeHead(500);
res.write(err.name);
res.end();
}
res.writeHead(200);
res.write(data);
res.end();
});
}
Is there any way to handle this request only with nodejs not using express or any other libraries?
Since req.url isn't going to be an exact match for case '/user/:id':, don't use a switch.
Use an if test using a regular expression instead.
if ( req.url.match(/^\/user\/\d+/);

Uploading mp3 files and playing the uploaded files in node.js

I am trying to upload some files, through an HTML form, in my local drive, which I was able to complete successfully. However, when attempting to play the mp3 uploaded file, by accessing the url of the "mp3 player", the server redirects me to the uploading page and I can not understand why this happens. I am quite a begginer, when it comes to node.js and I do not really know that much about JavaScript, as I have little experience with it. You can check the code below:
var http = require('http'),
fs = require('fs'),
filePath = './test.mp3',
stat = fs.statSync(filePath);
var formidable = require('formidable');
http.createServer(function(request, response) {
//fs.createReadStream(filePath).pipe(response);
if(request.url == '/playUploadedFile') {
fs.createReadStream(filePath).pipe(response);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size,
});
}
if (request.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = __dirname + '/' + files.filetoupload.name;
filePath = newpath;
console.log(filePath);
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
response.write('File uploaded and moved!');
//request.url = '/playUploadedFile';
response.end();
});
});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
response.write('<input type="file" name="filetoupload"><br>');
response.write('<input type="submit">');
response.write('</form>');
return response.end();
}
}).listen(8080)
In order to serve static file you have to declare your upload path to static. This way node understands the files within the specified path needs to be served exactly the way it is. The easiest way to do this is to use express https://expressjs.com/en/starter/static-files.html. But you can also use node-static https://www.npmjs.com/package/node-static package as well.

Node.js socket.io webserver provide other file than index.html

I started learn socket.io and use this example of chat.
When I go to ip:8080/public/index.html, I also need access to other files, for example other JS scripts, which will be used on client side in the browser. But when I put script load like this:
<script src="/js/phaser.js" type="text/javascript"></script>
the web server does not return it, and I need it on this handler code.
I have this code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8080);
function handler (req, res) {
console.log(req.headers.referer);
fs.readFile(__dirname + '/public/index.html', // <--- I need here put filename which client wants it, but when I console.log to req it return HUGE data, I not found anythink usefull
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
socket.broadcast.emit('new message', data);
console.log(data);
});
socket.on('msg', function(data){
console.log(data);
})
});
You can use Express static for serving static files like your *.js files.

Moved route from app.js to route.js and app no longer works

In my app.js file I had the code below and it worked as intended. I need to clean up my code, so I moved it to it's own route at routes/random and it no longer works because I get an error that states: "http://localhost:1337/random/1/1/testing 404 (Not Found)" and I am not sure why. My original code was in my app.js file when it was working was:
app.get('/random/:room/:userId/:message', function(req, res) {
fs.appendFile(room.number.toString(), req.params.message, function(err) {
if (err) {
console.log('error writing messages to file');
};
fs.readFile('./' + room.number, 'utf-8', function(err, data) {
if (err) {
if (err.fileNotFound) {
return this.sendErrorMessage('can\'t find the file, you linked it incorrectly');
}
console.log('error reading message file');
};
if (req.params.userId == 1) {
messages.user1.push(data);
} else {
messages.user2.push(data);
};
console.log(messages);
res.send(data);
fs.unlink(req.params.room, function(err) {
});
});
});
});
the new code includes the following for app.js
var express = require('express');
var app = express();
var fs = require('fs');
var random = require('./routes/random');
app.use('/random/', random);
app.use(express.static('public'));
app.use(express.static('public/js'));
app.use(express.static('public/images'));
and after I moved it, the route code is:
var express = require ('express');
var fs = require ('fs');
var random = express.Router();
random.get('/random/:room/:userId/:message', function(req, res) {
fs.appendFile(room.number.toString(), req.params.message, function(err) {
if (err) {
console.log('error writing messages to file');
};
fs.readFile('./' + room.number, 'utf-8', function(err, data) {
if (err) {
if (err.fileNotFound) {
return this.sendErrorMessage('can\'t find the file, you linked it incorrectly');
}
console.log('error reading message file');
};
if (req.params.userId == 1) {
messages.user1.push(data);
} else {
messages.user2.push(data);
};
console.log(messages);
res.send(data);
fs.unlink(req.params.room, function(err) {
});
});
});
});
module.exports = random;
Can anyone explain what I have done wrong that won't allow it to find the file?
In your code you are defining a route called random\random... in random.js, delete first random there, because middleware(app.use..) will direct all routes with /random to your router instance.
Your router is handling a url that starts with /random, and you attach this to your app under the path /random/. Remove one or the other (preferebly, the one inside the router).
I was able to fix it. Both comments above are correct, but it still was throwing errors due to my variables being undefined. I figured it out though so I am closing this question. Thank you both

Saving image to node.js server without express.js

So I have been wondering how to save an image to node.js server without the use of express.(just learning node and want to make everything myself to learn node better, without express).
So far I have a form with the image as only input which I send with a post request. This is what I have so far on my server, which does not log anything.
if(req.method === 'POST') {
if (req.url === '/upload') {
req.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
res.writeHead(200, {'Content-Type': 'image/jpg; charset=utf8'});
req.on('data', function (chunk) {
fs.writeFile(__dirname + "/uploads/dada.jpg", chunk, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
}
}
This is my form:
<form method="post" action="/upload" enctype="multipart/form-data">
EDIT: I fixed most of the problems, but the file is only saved as an image, but cannot be viewed like one. (Something is wrong with the content-type I guess, but don't know how to fix it)
Here is fiddle of my whole app. I know I need to separate it in different modules, but I will do that later
I completely forgot about this old question but now that I see it has quite some views, here is the solution I found:
var port = 1357;
var http = require('http'),
path = require('path'),
mime = require('mime'),
fs = require('fs'),
GUID = require('GUID'),
formidable = require('formidable'),
util = require('util');
var app = http.createServer(function (req, res) {
if (req.method === 'POST') {
if (req.url === '/upload') {
req.on('error', function (e) {
console.log('Problem with request: ' + e.message);
});
var fileDirectory = __dirname + '/db/',
form = new formidable.IncomingForm();
form.keepExtensions = true;
form.uploadDir =fileDirectory;
form.parse(req, function (err, fields, files) {
if (err) throw (err);
var pic = JSON.stringify(util.inspect(files)),
upIndx = pic.indexOf('db'),
path = pic.slice(upIndx + 6, upIndx + 42);
res.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('views/index.html', function (err, page) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(page);
res.write('<div>Download Link: </div><div>' + fileDirectory + path + '</div>');
res.end();
});
});
}
} else {
//not important for question, handle other request
}
});
app.listen(port);
console.log('Server running on port: ' + port)

Categories

Resources