Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run node.js in my web site server not my pc local server

Last 2 days I spent more time and read 50+ articles and video to understand node.js and after installation now I can see the result in browser by http//:localhost:3000/ But I have confused in many case that I describe below.

I do all of my work in my share hosting server where I my keep my web site: www.myweb.com

In every article about node.js, they are teaching how to get a result by below code in a browser by http//:localhost:3000/ in local pc server.

test.js

var http = require('http');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(3000);
console.log('Server running at http://localhost:3000/');

But My Question:

  1. If I use http//:www.myweb.com/test.js` in my browser, What will be the above code?

  2. In case of local pc we write on npm node test.js, But In case of hosting server when any clint open the page like http//:www.myweb.com/test.js How to work it?

  3. In case of php we used include ("head.php") to got something from that page But In this case How to make a call on node.js.

like image 801
koc Avatar asked Mar 20 '15 14:03

koc


1 Answers

Well, what you need to do is understand how http web servers works.

Usually, on your remote machine (your server), you have an instance of a web server (ex : apache) running, which is listening to port 80 (standard port for http requests). It will handle every request made on that port, and manage routing to use the correct php/html file.

Then, it will run the php code server-side, to render an html file and serve it to the server. So the client will not see the php code at all.

Let's talk about Node.js. Node is an application that runs javascript code server-side, and can run an http server with using some modules. But the javascript code will never be shown to your client, he will only get the http response you send him (typically, the html page).

So now, with node.js, you need to do the same as the apache server did, by creating the http server. First, what you have to know is that not that many website host are offering node.js, or even console access. They usually serve the php/html files you put in the configured folder, and that's basically it. What you need is either a virtual machine, or a server on which you can install node.js and run it, or use a node.js hosting service, like heroku or nodejitsu to host your node.js http server.

So, to create the node.js http server, you need to create an http server (as you did in your code), and make it listen to port 80. Now, every http request send to your server will be handled by your node.js instance. Then, you can do anything you want with that request.

I hope I haven't been to messy.

like image 197
Clément Berthou Avatar answered Nov 08 '22 11:11

Clément Berthou