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

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

问题描述

例如,如果您要运行Python脚本,则应键入 python filename.py ,或者如果您想运行C程序 make filename ,那么 ./ 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.

如果你掌握了为网页编写的脚本,您可能需要稍微包装或修改它以允许它接受来自stdin的参数并写入stdout。 (我相信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天全站免登陆