[javascript] Running Node.js in apache?

We have an Apache Webserver installed on a machine which also serves pages using Perl.

For a project I've decided to use Node.js instead of Perl/Ruby. Just wondering if it's possible to use Apache as my webserver (so it serves the pages) and use Node.js to dynamically create the web pages (this is for a web app I am creating)?

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

This question is related to javascript apache node.js webserver

The answer is


You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

No. NodeJS is not available as an Apache module in the way mod-perl and mod-php are, so it's not possible to run node "on top of" Apache. As hexist pointed out, it's possible to run node as a separate process and arrange communication between the two, but this is quite different to the LAMP stack you're already using.

As a replacement for Apache, node offers performance advantages if you have many simultaneous connections. There's also a huge ecosystem of modules for almost anything you can think of.

From your question, it's not clear if you need to dynamically generate pages on every request, or just generate new content periodically for caching and serving. If its the latter, you could use separate node task to generate content to a directory that Apache would serve, but again, that's quite different to PHP or Perl.

Node isn't the best way to serve static content. Nginx and Varnish are more effective at that. They can serve static content while Node handles the dynamic data.

If you're considering using node for a web application at all, Express should be high on your list. You could implement a web application purely in Node, but Express (and similar frameworks like Flatiron, Derby and Meteor) are designed to take a lot of the pain and tedium away. Although the Express documentation can seem a bit sparse at first, check out the screen casts which are still available here: http://expressjs.com/2x/screencasts.html They'll give you a good sense of what express offers and why it is useful. The github repository for ExpressJS also contains many good examples for everything from authentication to organizing your app.


Although there are a lot of good tips here I'd like to answer the question you asked:

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .

The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.

I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.

A quick example from cgi-node.org site:

<? include('myJavaScriptFile.js'); ?>
<html>
   <body>
      <? var helloWorld = 'Hello World!'; ?>
      <b><?= helloWorld ?><br/>
      <? for( var index = 0; index < 10; index++) write(index + ' '); ?>
   </body>
</html>

This outputs:

Hello World!
0 1 2 3 4 5 6 7 8 9

You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.

I am currently running Node.js through the cgi-node module on Godaddy.

CGI-Node.org site has all the documentation to get started.

I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.

Hope this helps.


The common method for doing what you're looking to do is to run them side by side, and either proxy requests from apache to node.js based on domain / url, or simply have your node.js content be pulled from the node.js port. This later method works very well for having things like socket.io powered widgets on your site and such.


If you're going to be doing all of your dynamic content generation in node however, you might as well just use node.js as your primary webserver too, it does a very good job at serving both static and dynamic http requests.

See:

http://expressjs.com/

https://github.com/joyent/node/wiki/modules


While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.

In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.


Hosting a nodejs site through apache can be organized with apache proxy module.

It's better to start nodejs server on localhost with default port 1337

Enable proxy with a command:

sudo a2enmod proxy proxy_http

Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large. Setting ProxyRequests to Off does not disable use of the ProxyPass directive.

Configure /etc/apche2/sites-availables with

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName site.com
    ServerAlias www.site.com 

    ProxyRequests off

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        ProxyPass http://localhost:1337/
        ProxyPassReverse http://localhost:1337/
    </Location>
</VirtualHost>

and restart apache2 service.


If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:

<?php
    shell_exec("node nodeScript.js"); // without arguments
    shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>

The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:

<?php
    $evilUserData = "'; [malicious commands here];";
    shell_exec("node nodeScript.js '{$evilUserData}'");
?>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to apache

Enable PHP Apache2 Switch php versions on commandline ubuntu 16.04 Laravel: PDOException: could not find driver How to deploy a React App on Apache web server Apache POI error loading XSSFWorkbook class How to enable directory listing in apache web server Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to enable php7 module in apache? java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to webserver

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests Apache Server (xampp) doesn't run on Windows 10 (Port 80) What is the difference between HTTP 1.1 and HTTP 2.0? Reload nginx configuration The program can't start because MSVCR110.dll is missing from your computer XAMPP Object not found error Amazon AWS Filezilla transfer permission denied how to configuring a xampp web server for different root directory How to open a web server port on EC2 instance Minimal web server using netcat