Search code examples
node.jsraspberry-piwebserver

Setting up a web server with node.js on a Raspberry PI


I am trying to set up a web server using node.js on a Raspberry PI 4 (Model B).

I have read a few tutorials to get started, but I can't finish putting the pieces together.

I have installed apache2 on the PI and I can see the web server working (with the default page) using apache2 by pointing a browser from another computer.

I have also installed node.js, I can confirm on the command line that it is working like this:

pi@raspberrypi:/var/www/html $ node -v
v18.12.0
pi@raspberrypi:/var/www/html $ npm -v
8.19.2
pi@raspberrypi:/var/www/html $ 

Beside I have a page index.js on my local computer that I can see locally. Starting the server with:

$ node index.js

And then using the browser to see the result.

I want to bring index.js to the PI and then serve it from there.

What do I need to do to achieve that?


Solution

  • Here is what has to be done to reach the goal.

    1. Create a directory somewhere on the PI. For example:

      $ mkdir /home/myHomeDir/WWW_MyNodeSite

    2. Using scp or any other similar tool, copy index.js from the local computer to the PI under the newly created directory (WWW_MyNodeSite).

    3. On the PI go to the new directory:

      $ cd /home/myHomeDir/WWW_MyNodeSite

    4. Here start the server:

      $ node index.js

    And that's it; the server is now running on the PI and can be accessed from any web browser.

    1. One more information point:

      apache2 is not needed for this to work.