Run a Javascript file in Terminal window

In order to run a Javascript file in a Terminal window, the file must first be saved with a ".js" extension. Then, the file can be run using the command "node filename.js".

// Create a JS file - script.js and put below code
function sum(a, b) {
    console.log(a + b);

sum(5, 10);

// run below command
// -> node script.js

If you have a Javascript file that you want to run in a Terminal window, there are a few steps you need to follow. First, open the Terminal application. Next, navigate to the directory where your Javascript file is located. Then, type the below command into the Terminal window:

node <filename.js>

Replace <filename.js> with the name of your Javascript file. Finally, press the Enter key to run the file.

Nodejs must be installed on your system to execute the Javascript file from the terminal.

Was this helpful?