Run a JavaScript Script File from the Terminal on Mac

mac
2014-06-13 12:00 (10 years ago) ytyng
#!/usr/bin/env jsc
print("Hello, World!");

To execute such a JS file from the terminal, it's convenient to use the JSC that comes pre-installed on Mac.

1. Add JSC Interpreter to Your Path

The JavaScript interpreter on a Mac is located here:

/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc

Since it's not in the PATH by default, create a symbolic link in a directory that is in the PATH.

For example, you might use /usr/local/bin.

cd /usr/local/bin
ln -s /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc ./

In the terminal, run:

jsc --help

If the help information is displayed, it's set up correctly.

1.1. Using the Interactive Interface

Run:

jsc

This will start an interactive interface. The prompt and behavior are very similar to Python's interactive interface.

You can even write functions.


2. Write Your JS File

#!/usr/bin/env jsc
print("Hello, World!");

Save this as hello.js.

3. Make the File Executable

chmod +x hello.js

4. Execute the File

./hello.js



Reference:

Running JS in Mac's Terminal - modified's diary

Current rating: 4.5

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011