JavaScript

How to run JavaScript through the terminal

JavaScript is a handy language to practice in modern-day tools and technologies. If you start learning JavaScript from now on, it can lead you to a powerful base for web-based client and server-side scripting. Unlike other languages like C or Java which need to be compiled before running, JavaScript is the interpreted language that does not need any compiler.

If you have written a few lines of code in JavaScript and you’re not able to figure out how to see the results of it or how to run it! This is the write-up in which I’ll be explaining how you can easily run the JavaScript code through a terminal or command prompt.

You may run a JavaScript console in a terminal or other command-line interface using Node.js(an open-source, cross-platform runtime that executes JavaScript outside of a web browser).

Running JavaScript in Terminal

This is how you can easily run JavaScript through your terminal/Command prompt

  • Install Node.js
  • Run the JavaScript code using the ‘node (filename).js’ command

Installing Node.js

Visit the Node.js website to download the latest version of Node.js depending on if you’re using Mac, Windows, or Linux, and install it in your system. Note that download the stable version of the Node.js.

After installing the Node.js in your system, open the command prompt and type:

$ node --version

You will see the following output:

Note: If you want an in-depth guide on how to install NodeJs then you can visit this extensive guide.

Running the JavaScript file

Let’s see how we can run our JavaScript file in the terminal using node. First of all, create a file demo.js or whatever name you want to give to your JavaScript file like so:

Write some JavaScript code in it.

let Name = "Shahroz Azam"

console.log("Hello world, My name is: "+ Name)

After writing the code inside your JavaScript file, now prompt yourself to the folder where you have created that JavaScript file, for my case it’s inside E:\\ directory.

So, use terminal to first navigate it to E: drive:

Type the following command:

$ node demo.js

You will see the following output:

Congratulations you’ve successfully run your first JavaScript file inside the terminal.

Conclusion

By installing Node.js on your system, you can run JavaScript code in the terminal. After installing, you can use the node command with the name of the JavaScript file and that will be it for running the JavaScript in the terminal. In this article, we have seen how we can install Node.js and how we can use Node.js to run our JavaScript code in the terminal.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.