Coder Perfect

How do you run JavaScript script through the Terminal?


For example, if you wanted to execute a Python script, type python, or if you wanted to launch a C program, type./ filename. What’s the best way to do this with.js files?

Asked by BLUC

Solution #1

Another option is to use NodeJS!

You may start it with the node command at the terminal.

$ node
> 2 + 4

Note: To exit, simply type ‘exit’.


You can also use a JavaScript file, such as this one:

node file.js

« Get it RIGHT NOW »

Answered by Ionică Bizău

Solution #2

You can access a javascript console in OS X (Terminal) if you have a Mac by typing jsc.



You could also use jsc to launch one of your.js scripts by passing its name as an argument:

jsc your_awesome_script_name.js

During development, I use console.log(), but jsc requires the debug() function.

On Ubuntu, you have access to a number of useful ECMAScript shells. It’s worth mentioning SpiderMonkey among them. It may be installed with sudo apt-get install spidermonkey.

On Windows, you can rely on cscript and wscript, which are incorporated into the operating system.

I’d also suggest another:) approach to the problem; if you have time and enjoy learning new things, I’d recommend coffee-script, which comes with its own compiler/console and produces super-correct Javascript. You can also test it in your browser (link “try coffeescript”).

UPDATE (July 20, 2021): You may also install and use the fantastic QuickJS, which can be done using brew install quickjs on OS X. After that, an interactive console with qjs will be available at your propmt.

Answered by microspino

Solution #3

To evaluate the script, you’ll need a JavaScript engine (such as Mozilla’s Rhino), just as you would for Python, but Python comes with the standard distribution.

If you have Rhino (or any equivalent) installed and in your path, running JS can be as simple as clicking a button.

> rhino filename.js

While JavaScript is a standalone language, many scripts expect they’ll be running in a browser-like environment, so they try to access global variables like location.href and make output by attaching DOM objects rather than calling print.

You may need to encapsulate or alter a script developed for a web page to allow it to receive parameters from stdin and output to stdout. (I believe Rhino has a mode that emulates typical browser global vars, but I can’t find the documentation right now.)

Answered by Andrzej Doyle

Solution #4

Use node.js for this; here’s an example of how to install node on a Mac using brew:

brew update && install node

Then type node filename.js to start your program, and use console.log() for output.

Answered by Andrey Bodoev

Solution #5

It’s clumsy, but you can paste the text contents of the *.js file into the Javascript terminal in Chrome (Ctrl+Shift+J) and push Enter.

Answered by Mark Lakata

Post is based on