如何通过终端运行 JavaScript 脚本? [英] How do you run JavaScript script through the Terminal?

查看:29
本文介绍了如何通过终端运行 JavaScript 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果您要运行 Python 脚本,您可以输入 python filename.py 或者如果您要运行 C 程序 make filename 然后 ./文件名.你如何用 .js 文件做到这一点?

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. How do you do this with .js files?

推荐答案

您需要一个 JavaScript 引擎(例如 Mozilla 的 Rhino) 以评估脚本 - 与您对 Python 所做的完全一样,尽管后者随标准发行版一起提供.

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.

如果您安装了 Rhino(或替代)并且在您的路径上,那么运行 JS 确实可以像

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

> rhino filename.js

值得注意的是,虽然 JavaScript 本身就是一种语言,但许多特定的脚本假定它们将在类似浏览器的环境中执行 - 因此尝试访问全局变量,例如 location.href,并通过附加 DOM 对象而不是调用 print 来创建输出.

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.

如果您掌握了为网页编写的脚本,您可能需要对其进行一些包装或修改,以允许它接受来自标准输入的参数并写入标准输出.(我相信 Rhino 有一种模拟标准浏览器全局变量的模式,这很有帮助,但我现在找不到相关文档.)

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

这篇关于如何通过终端运行 JavaScript 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆