nodejs and socket.io.js path resolution - node.js

I have just started learning nodejs with the socket.io.js library. My question isn't really related to the stuff in these libraries but rather on how the files are served by a visiting browser.
In my server directory there are just 2 files present (index.html and server.js) along with the node_modules directory (for socket.io). In the index.html I have a script tag including the client side socket.io lib as follows,
<script src="/socket.io/socket.io.js"></script>
The relecvant server code is,
var server = http.createServer(
function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}
).listen(8080,
function() {
console.log('Listening at: http://localhost:8080');
}
);
My question is where is this file present on the server (there is no socket.io directory in the dir where index.html is present)? So how and from where is this being resolved and downloaded correctly by the web browser?
Sorry for the noob question.

The client side file is injected by the socket.io npm module automatically so that when you upgrade the npm module your client side version of socket.io gets updated automatically.
The actual file lives at:
/usr/local/lib/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
Edit: Forgot to mention that when you initialise socket.io you are actualy making it start its own server that serves the file.

Related

Socket.io how create file run time on local server

I have written down this code in NPM module with the help of socket.io,
Index.html
<html> <head> <title>WebRTC client</title> </head> <body>
<script src='socket.io/socket.io.js'></script> </body> </html>
In server.js file
var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function (req, res) {
file.serve(req, res);
}).listen(8181);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket){
console.log('io.sockets.on');
});
Root folder has index.html, server.js, and socket.io folder contains no file
Hit localhost:8181 in a browser, index.html will run and socket.io/socket.io.js file automatically created
http://localhost:8181/socket.io/socket.io.js
and I checked my socket.io folder there is no file? How socket.io.js created? and what is the main purpose of a socket.io/socket.io.js file?
"You might be wondering where the /socket.io/socket.io.js file comes from, since we neither add it and nor does it exist on the filesystem. This is part of the magic done by io.listen on the server. It creates a handler on the server to serve the socket.io.js script file."
from the book Socket.IO Real-time Web Application Development, page 56

Can i use node as webserver for html app?

I'm sorry to ask such a simple question. I've been sent files by someone, an index.html file which pulls in a js file within script tags. I have to start a webserver to get through authentication and view the files (am in dev).
In my CLI i have navigated to the directory containing index.html. I have checked with node -v that I have it installed globally (yes, v 8.6). I've run the simple command node and checked my browser at http://localhost:3000 and a few other ports but get no joy. I've also tried node index.html but CLI throws an error.
How do i start the webserver? All the examples online tell me to build a .js file, but this is not an option.
Steps to set up a node web server
Create the route folder from your local machine.
Go to the command prompt from the project root path.
Install express using the command npm install express
Create server.js file
create the folder wwww and create the Index.html inside it.
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/www'));
app.listen('3000');
console.log('working on 3000');
Index.html
<!doctype html
<html>
<head>
<title> my local server </title>
</head>
<body>
<h1> server working </h1>
<p> just put your html,css, js files here and it work on your own local nodejs server </p>
</body>
</html>
Go to the project root path and take the command prompt, then start the server by running the command node server.js
Then go to the browser and run the url localhost:3000.
Now you can see the html page will render on your browser.
Since you don't want to build a backend but just an http server.
I would propose to use an npm package that do just what you need:
Open a console
npm install http-server -g
Go to your "index.html" folder (in the console) then type:
http-server
Then reach your content in your browser at this address:
http://localhost:8080
Documentation here:
https://www.npmjs.com/package/http-server
Yes, this is possible.
A very simple example of how to do this would be to create file, let's call it app.js and put this in it:
const http = require('http'), // to listen to http requests
fs = require('fs'); // to read from the filesystem
const app = http.createServer((req,res) => {
// status should be 'ok'
res.writeHead(200);
// read index.html from the filesystem,
// and return in the body of the response
res.end(fs.readFileSync("index.html"));
});
app.listen(3000); // listen on 3000
Now, run node app.js
Browse to http://localhost:3000
There's loads of other npm packages that will help you out do this, but this is the simplest 'pure node' example to literally read index.html and serve it back as the response.
Its very easy to start a server using node js
Create a server.js file,
const http = require('http')
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(3000);
Run node server.js
Here is a reference
This will even solve your backslash issue by this

socket.io including in project and installation

Im want to include socket.io in my project. I installed it using npm install -g socket.io still being in directory my files to the project are located in.
I created script to test if it was successfull
i creater server.js with code
var client=require("socket.io").listen(8080).sockets;
client.on("connection",function(socket){
console.log("Someone has connected")
})
and included in html file
<script type="text/javascript" src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
I tried to run node server.js to see if there will be message in console but there wasnt , . Whad did i do wrong? I a trying to solve this problem but can find solution. Thanks for helping.
You must initialize a connection in html file (on client side).
If you are trying to connect to the host that serves the page you can use:
var socket = io();
or specify address:
var socket = io.connect('http://127.0.0.1:8080');

Start nodejs in browser form begining?

I am new in Nodejs and using Mac OS (MAMP, localhost:8888), I have already installed and I can execute programs in terminal. But how to in build with html. Can, we include nodejs as a external library like (jQuery, Bootstrap).
Please refer this Hello world example.
node.js
var http = require("http");
var server = http.createServer(handler);
var fs = require('fs');
server.listen(3003)
function handler(req,resp){
fs.readFile("index.html",function(err,data){
if(err){
console.log("error in loading file.");
resp.end("failed to load")
}else{
resp.writeHead(200);
resp.end(data)
}
})
}
HTML
<html>
<head>
</head>
<body>
Hello world.!!
</body>
</html>
Once you mentioned port number in listen function,
node server will run on that port.So until you are not giving same port number as Apache,you can run both Apache and nodejs parallel.If your Apache and nodejs server sharing same port number , then you need to stop one of them in order to use other.
Your Question :
Can, we include nodejs as a external library like (jQuery, Bootstrap).
Node.js is not library.So you can not include it like jQuery or bootstrap.
It is platform for javascript to run on server side.And using nodejs we can create Server which serve your content of Web like Apache do.
When you say node app.js (insead of app.js it can be any name) from your command prompt,you starting your node server.
In above example index.html you can include your jQuery or angular or bootstrap library as you do when using Apache

display html page with node.js

This is my first time with node.js. I get it to display the index.html, but it doesn't display the images on the site or anything else, it ONLY shows the basic html stuff. Here's how I set it up.
There's no apache, php or anything else on the server, just ubuntu, proftp and node(and curl and the other dependencies). I made the main directory for the node files /var/nodeFiles and the directory for the html/site files is /var/nodeFiles/www
so for my node server file I did it like this:
var http = require('http'),
fs = require('fs');
fs.readFile('/var/nodeFiles/www/index.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(80);
});
this works, but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display. The files and directories are all correct, I've double checked and the permissions of the folders are correct. So what else do I have to do to get node to display the rest of the site?
I hope I've explained my self correctly, I was told this is the place to ask development questions.
Thank you for taking the time to read this.
but it ONLY shows the index.html file and NOTHING attached to it, so no images,
no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
Check this basic code to setup html server. its work for me.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.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(8000);
});
This did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
Update 1/28/2014:
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
End Update
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$#"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
You can simply use
res.senFile('PATH_TO_FILE');

Resources