Running JavaScript Code from Node.js Shell

It is assumed that you have Node.js installed in your system. If not, detailed instructions on installing Node.js via the package manager can be found following the link below

https://nodejs.org/en/download/package-manager/

js nodejs shell

To quick test if the installation is correct, check the version of Node.js installed from the terminal

				
				node -v
				
			

It should give the version number, something like v11.12.0.

The Node.js interactive shell can be started by executing node from the terminal

				
				node
				
			

The command line prompt > will appear. This is also called the REPL (Read-Eval-Print-Loop).To print Hello, World!, run the below command

				
				> console.log("Hello, World!");
				
			

and it will log the message Hello, World! into the shell along with undefined below it. That is the console.log's return value, which, in this case, does not return anything.

JavaScript code snippets can be typed into the interactive shell for testing and experimenting. Given below are just a few examples indicating

  • adding of two numbers

    							
    							> 1+1;
    							
    						
  • getting the current date and time

    							
    							> Date();
    							
    						
  • looping through arrays

    							
    								> ['a','e','i','o','u'].forEach(function(v){console.log(v);});
    							
    						

Running JavaScript File

A JavaScript program file can be run from a Node.js shell by exporting it as a function inside a module. A simple hello.js module to print "Hello, World!" would look like

					
					exports.hw = function(){
						console.log("Hello, World!");	
					}
					
				

Now launch the Node.js shell typing node from the terminal

					
						node
					
				

Load the hello.js module, assigning its return value to the variable h

					
					> var h = require("./hello");
					
				

And finally, call the function hw

					
					> h.hw();
					
				

which prints Hello, World! into the shell.

Executing Explicitly

The hello.js script file can also be executed explicitly by specifying the Node.js interpreter. Comment out or remove the exports.hw line (and its closing braces), keeping only the console.log("Hello, World!"); line in the program. The hello.js now is just a one-line program

					
					//exports.hw = function(){
						console.log("Hello, World!");	
					//}
					
				

Assuming that you are in the same location as hello.js, type

					
						node hello.js
					
				

in the terminal and the script will be executed. If you are in some other location, specify the path to hello.js after the node command.