JavaScriptをターミナルで実行する方法
auです。
Pythonだったら
python test.py
C言語だったら
./a.out
このように、ターミナル上でファイルを実行して結果を得ることができます。
そういえばJavaScriptでやったことないなと思ったので調べてみました。
やり方
Macではデフォルトで存在する「JSC」というインタプリタがあるようです。
やってみましょう
jsc --help bash: jsc: command not found
参考にあるように、初期状態ではパスが通っていないようです。まずはファイルを確認しましょう。
ls /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/ BridgeSupport/ Info.plist framework.sb version.plist
あれ、jscがない・・・
コメントを読んでみると移動しているようですね。
ls /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Helpers/ jsc*
ResourcesからHelperになっていました。
このパスを通します。
cd /usr/local/bin/ ln -s /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Helpers/jsc ./
もう一度jscを使ってみます。
jsc -h jsc -h Usage: jsc [options] [files] [-- arguments] -d Dumps bytecode (debug builds only) -e Evaluate argument as script code -f Specifies a source file (deprecated) -h|--help Prints this help message -i Enables interactive mode (default if no files are specified) -m Execute as a module -s Installs signal handlers that exit on a crash (Unix platforms only) -p <file> Outputs profiling data to a file -x Output exit code before terminating --sample Collects and outputs sampling profiler data --test262-async Check that some script calls the print function with the string 'Test262:AsyncTestComplete' --strict-file=<file> Parse the given file as if it were in strict mode (this option may be passed more than once) --module-file=<file> Parse and evaluate the given file as module (this option may be passed more than once) --exception=<name> Check the last script exits with an uncaught exception with the specified name --watchdog-exception-ok Uncaught watchdog exceptions exit with success --dumpException Dump uncaught exception text --footprint Dump memory footprint after done executing --options Dumps all JSC VM options and exits --dumpOptions Dumps all non-default JSC VM options before continuing --<jsc VM option>=<value> Sets the specified JSC VM option --destroy-vm Destroy VM before exiting Files with a .mjs extension will always be evaluated as modules.
うまく行きました!
ちなみに、「ln」の部分で間違えてResourcesのバージョンでパスを通してしまった場合は、オプションに「-i」を追加してください。上書きするか聞かれるので「y」で答えれば修正できます。
実行する
color_list = ['red', 'blue', 'green', 'brack'] color_list.forEach(function(color) { print(color) })
jsc test.js red blue green brack
console.logではなくprintで出力するところで数分悩んでました。