You can run Node.js application an console based or web-based application. Console based application will run your system terminal and a web-based application will use an inbuilt web server to make an application accessible on the web browser.
Console-based Hello World Example
Use the Node.js console module to print output on your system console. Create a JavaScript file
Execute your script using the node
node nodejs_hello_console.js [output] Hello World!
Web-based Hello World Example
A Node.js web application is build with 3 parts.
- Import module to create web server
- Create a web server
- Read client requests and send reponse back to client
Below is the sample application uses http module. http module creates a web server similar to Apache or Nginx web servers. Now create a server with specified host and port. Use used 0.0.0.0 host address means it will listen on all interfaces attached to the system.
Create a JavaScript file
Execute the script using node. It will start a web server on specified port and host.
node nodejs_hello_web.js [output] Web server running at http://0.0.0.0:3000
For example, above script started a web server on port 3000. Visit your server on a defined port in the web browser. It will show you the result like below.