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:
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.
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:
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.