How do you run JavaScript script through the Terminal?

前端 未结 16 1796
离开以前
离开以前 2020-12-02 04:00

For instance, if you were to run a Python script you would type python filename.py or if you wanted to run a C program make filename then ./ filename

16条回答
  •  长情又很酷
    2020-12-02 04:33

    You would need a JavaScript engine (such as Mozilla's Rhino) in order to evaluate the script - exactly as you do for Python, though the latter ships with the standard distribution.

    If you have Rhino (or alternative) installed and on your path, then running JS can indeed be as simple as

    > rhino filename.js
    

    It's worth noting though that while JavaScript is simply a language in its own right, a lot of particular scripts assume that they'll be executing in a browser-like environment - and so try to access global variables such as location.href, and create output by appending DOM objects rather than calling print.

    If you've got hold of a script which was written for a web page, you may need to wrap or modify it somewhat to allow it to accept arguments from stdin and write to stdout. (I believe Rhino has a mode to emulate standard browser global vars which helps a lot, though I can't find the docs for this now.)

提交回复
热议问题