Using Node.js to Run JavaScript

One of the things that I love about Node.js is how easy it is to run and test JavaScript code. This speeds up development by enabling you to easily test functions and snippets without a web browser or web server. There are two main methods to run JavaScript code using Node.js.

The first method to run JavaScript using Node.js is to simply type the JavaScript code directly in the Node.js shell. This is the method you used in the preceding section where you printed Hello on the screen. One thing to note is that when you execute commands in the Node.js shell, the result of those commands is also displayed along with the output. If the statement being executed does not return a result, then the word undefined is displayed. That is why you saw an undefined also printed after the Hello.

The second method to run JavaScript using Node.js is to create a JavaScript file and then execute it from the console prompt. For example, you can also create a file named hello.js with the following contents:

console.log("Hello");

Then you can run that JavaScript file from the console prompt using the following command:

node hello.js

This assumes that hello.js is in the current location in the console. If the JavaScript file is in another location, you will need to specify the path to that file. For example:

node path_to_file/hello.js

The final method to run JavaScript using Node.js is to use the require() method either from the Node.js shell or in a JavaScript file that is being executed from the command line. The require() method will load and execute a JavaScript file. This enables you to import functionality from the external JavaScript file. For example:

require("path_tofile/hello.js");

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset