Node.js example scripts

Overview

This article lists a few simple Node.js examples you can use to test your installation.

Command line example

Create and run this script within your terminal:

  1. Create a file named HelloWorld.js, and then add the following in the file:
    console.log('Hello World!');
  2. Run the following in your terminal to run the script:
    [server]$ node HelloWorld.js
    Hello World!
    

    If correctly installed, you will see the console respond with Hello World!

Website example

You can also create a basic HTTP server to load a site.

  1. Create a file in your web directory named server.js with the following code:
    var http = require("http");
    
    http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write("Hello World. This page is running Node.js version: ");
      response.write(process.version);
      response.end();
    }).listen(8888);
    
    • This HTTP server will listen on port 8888.
  2. Start the server by running the following:
    [server]$ node server.js
  3. Visit the page in a browser with port 8888 appended to the end. For example:
    http://example.com:8888
    If running correctly, your site will display the following:
    Hello World. This page is running Node.js version: v12.16.3

Loading your application on port 80 and 443

If you have enabled Passenger in your panel for Node.js, and the file to load your application is named app.js, your Node.js site will automatically load on port 80 and 443 without needing to manually start the server. View the following article for further details.

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?