简体   繁体   中英

Running Node.js on a server

So I have Node.js installed on my server.

However, I'm a little confused about the next bit. I've spent a few hours researching about Node.js but I can't seem to find any clearly-laid out info on what I'm looking for.

On my host PC, I can run Node.js through the command prompt and loading up localhost:port in the browser. This works fine. However, I can't figure out how this would translate onto using Node.js on my VPS. As I mentioned, it's installed. But how would I use physically use Node.js in my programs, and be able to access it on the pages when needed?

I'm usually a PHP developer but I'm using this chance to dive into the world of Node and pick it up, and begin using it instead of PHP.

Thank you for the help.

Node.js is a little different to how you're used to using PHP, in that it doesn't replace PHP but PHP and Apache .

Your Node.js program is responsible for accepting every request and deciding how you respond to it. It isn't just something you can "access on the pages when needed", it serves the pages itself.

For example, instead of serving an index.php containing code to run when you visit http://example.com/ , your Node.js server would contain code to run when you visit http://example.com , and decide how to handle the path / :

index.php

<?php
echo 'Hello world';

server.js

var http = require('http');
http.createServer(function(req, res) {
  if(req.url === '/') {
    res.end('Hello world');
  } else {
    res.statusCode = 404;
    res.end(req.url + ' not found');
  }
}).listen(3000);

Node.js is typically used with Apache or Nginx or [insert server here] as a reverse proxy , to forward external requests on to an internal Node.js server.

If all this sounds a little daunting, and you're thinking "why can't I just embed Node.js in pages like PHP", there's always PNP . However, it's probably not suitable for production usage, and at that point you might as not be using Node.js, as you won't have access to any asynchronous APIs, which includes pretty much everything.

I'd recommend the Node.js for PHP Developers blog series, which serves as a great introduction to the major concepts of Node.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM