Error in loading javascript file from node.js - javascript

I am trying to use node.js code to run the data in local host, but after I run the code, the javascript file that link inside the Admin Page.html is not running in localhost , and the font file src that wrote inside the Admin Page.html is also not running.How do i fix that? my javascript file is AdminPage.js
complete code for Admin Page.html and AdminPage.js is inside :
https://jsfiddle.net/szeYun/25x6bqLn/
var http =require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
if (req.url != '/favicon.ico'){
console.log('The request made is: '+ req.url);
}
res.writeHead(200,{'Content-Type':'text/html'});
//res.end('Hello World');
var myReadStream = fs.createReadStream(__dirname + './Admin Page.html' , 'utf8');
myReadStream.pipe(res);
});
server.listen(3000, function(){
console.log('Now the server is listenening on port 3000');
});
https://jsfiddle.net/szeYun/25x6bqLn/

Related

Node.js connection with socket.io not working

Hey guys that's one of my first time using node.js and socket.io so i will try to be clear as possible. So i am doing a tutorial for a chat.
And i don't know why the connection is not working when i am running my html page :
http://localhost:8000/user/tchat (Symfony project)
I don't have the
console.log('New user'); (i run the server with "node server.js")
But when i am going to :
http://localhost:1337/
i have the
console.log('This is a test');
I have 2 js files and one html page :
Server.js :
var http = require('http');
httpServer = http.createServer(function(req, res) {
console.log('This is a test');
res.end('Hello World');
});
httpServer.listen(1337);
var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function(socket) {
console.log('New user');
});
Client.js :
(function($){
var socket = io.connect('http://localhost:1337');
})(jquery);
And the scripts of the html page :
<script src="http://localhost:1337/socket.io/socket.io.js"></script>
<script src="../js/js/client.js"></script>

Send upload progress update to client using node.js, node-formidable and socket.io

My code shows a simple upload form (node-formidable and node.js). I am using socket.io to update the client on it's current upload file progress. My problem is that I currently emit the progress update to every clients. As an example, if I start an upload with clientA, then connect to the website with clientB, clientB will see the exact same progress bar as clientA. Normally, clientA and clientB should be different, with their own respective progress bars, linked only with their respective uploads.
This is my app.js file
// Required modules
var formidable = require('formidable'),
http = require('http'),
util = require('util'),
fs = require('fs-extra');
// Path to save file, server side
var savePath = "./uploadedFiles/";
// Loading index.html
var server = http.createServer(function(req, res) {
// Form uploading Process code
//Upload route
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// creates a new incoming form.
var form = new formidable.IncomingForm();
// set the path to save the uploaded file on server
form.uploadDir = savePath;
// updating the progress of the upload
form.on('progress', function(bytesReceived, bytesExpected) {
io.sockets.in('sessionId').emit('uploadProgress', (bytesReceived * 100) / bytesExpected);
});
// parse a file upload
form.parse(req, function (err, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('Upload received :\n');
res.end(util.inspect({ fields: fields, files: files }));
});
form.on('end', function (fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Files are nammed correctly */
fs.rename(temp_path, savePath + file_name, function(err) {
if ( err ) console.log('ERROR: ' + err);
});
});
return;
}
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// socket.io
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.join("sessionId");
});
server.listen(8080);
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Test d'upload</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('uploadProgress' , function (progress){
document.getElementById("currentProgress").value = progress;
});
</script>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
<p><progress id="currentProgress" value="0" max="100"></progress></p>
</body>
</html>
I do not have more code than this. I am new to node.js and socket.io, so I am not sure about the interactions between them and between the client and server.
How can I change my code to update only the right client?
Thank you anyway for your time.
a suggestion
there is a basic way
socketIO.sockets.socket(this.socketid).emit(<event>, dataObj);
if your function is inside your socket code...otherwise I will often do something like this
connection.query("select socketid from websocket_sessions where user_id=" + data.form.user_id, function(err, users) {
socketIO.sockets.socket(users[0].socketid).emit(<event>, dataObj);
});
where I am always updating or a

NodeJS res.sendFile not sending images or directorys

so as said above, i run the html file only and i'm able to see the pictures, but when i run the file via node it sends me a 404 error on the file i used.
<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>
and the node code
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
how can i stop this from happening?
To serve static files such as images and scripts, you need to include a middleware that serves static files. Put all your static files inside of a public directory and serve them like this.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});

Express js chat application:404 error on socket.io.js file

I am trying to develop a chat application using Express js(jade template ) and socket.io.Here is my app.js
var express = require('express');
var path = require('path');
var http = require('http');
var io = require('socket.io')(http);
var app = express();
//start chat with socket io
io.sockets.on('connection',function(socket){
console.log("connection");
socket.on('send message',function(data,callback){
var msg=data.trim();
if(msg==null){
callback("enter a messsage");
}else{
console.log("chat message"+msg);
io.sockets.emit('new message',{msg:msg});
}
});
});
//end socket
Here is my chat.js file on client side
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
var $message=$('#message');
var $messageForm=$('#send-message');
//opens a connection and send to sever
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',$message.val(),function(data){
console.log("data"+data);
});
$message.val('');
});
//read the chat messages from users
socket.on('new message',function(data){
console.log('data.msg');
});
});
chat.jade file
<form id="send-message">
<input type="text" id="message">
<input type="submit" value="submit"/>
</form>
<script src="http://localhost/api/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
I will get 404 error on this file http://localhost:3000/socket.io/socket.io.js. Also get a Uncaught ReferenceError: io is not defined in chat.js script.I think this is because of missing socket.io.js file.
You have a couple of issues.
Serving static files in your jade templates you should be using something like this:
link(rel='text/javascript', href='/js/socket.io.js')
These files will normally be contained within a public directory in your express app.
Then in your app.js you should have something like:
app.use(express.static('public'));
Its explained here on the express site - http://expressjs.com/starter/static-files.html
Elsewhere
Uncaught ReferenceError: io is not defined
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
This is because you havent defined io on your client. You call connect on something called io but havent declared/defined io anywhere.
Also
You havent created a socket server on your app side. You should be doing something along the lines of:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
});
});
Example
Socket.io have an example chat app on github that you should use as reference.
Your chat.js would be the equivalent of their public/main.js
Your chat.jade is equivalent to their public/index.html
and your app.js matches their index.js

how can i include JavaScript file in node.js app?

i am accessing the script.js and libs.js in index.html like this:
<body style='margin:0px' >
<canvas id='your_canvas'
style='position: absolute; background-color: black;'></canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/libs.js"></script>
<script type="text/javascript" src="/script.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
but the .js files cannot be accessed and showing error:
1) GET script.js 404 (Not Found) localhost/:12.
2) GET libs.js 404 (Not Found) localhost/:11.
3) Uncaught ReferenceError: main is not defined (index):17.
where am i going wrong and how can i include these two JavaScript files using node.js?
my app.js is :
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server);
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public/script.js'));
app.use(express.static(__dirname + '/public/libs.js'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
and then i have my script.js and libs.js files.
You need to actually serve these files if you want them to be accessible. You can't just include them in your project directory. If you are using Express, you can designate a static file directory like this:
app.use(express.static(__dirname + '/public'));
You can also use node-static or even create a handler for each file...
Using express, your code should look something like this (Not tested):
var express = require("express");
var app = express();
app.server = require('http').createServer(app);
var io = require("socket.io").listen(app.server);
app.get('/', function(req, res){
res.sendfile(__dirname + '/public/index.html'); // I would move this file to public
});
app.use(express.static(__dirname + '/public'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
app.server.listen(8000);
Are you trying to call:
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
If you are then you need to save your code as a file named script.js in the root directory. Adding javascript/jQuery between tags in your html does not need to be called and will run automatically.
I'd advise laying your script out in the following way too, i don't recognize the way you have laid it out.
<script>
var main = function() {
\\Your javascript/jQuery
}
$(document).ready(main);
</script>

Categories