例如,如果你要运行一个Python脚本,你会键入Python filename.py,或者如果你想运行一个C程序,make filename then ./ filename。如何使用.js文件做到这一点?


当前回答

你需要像Node一样安装JS引擎,然后在你的文件的第一行使用shebang行,像这样:

script.js

#!/usr/bin/env node
console.log('Hello terminal');

之后,您必须设置可执行权限:

chmod +x 脚本.js

然后运行它

./script.js

其他回答

它很粗糙,但你可以在Chrome中打开Javascript控制台(Ctrl+Shift+J),粘贴*.js文件的文本内容,然后按Enter。

使用node.js,下面是如何在mac上使用brew安装node的例子:

brew update && install node

然后通过输入node filename.js运行程序,然后可以使用console.log()进行输出。

你需要像Node一样安装JS引擎,然后在你的文件的第一行使用shebang行,像这样:

script.js

#!/usr/bin/env node
console.log('Hello terminal');

之后,您必须设置可执行权限:

chmod +x 脚本.js

然后运行它

./script.js

从技术上讲,Node.js不是我们所知道的正确的JavaScript,因为没有文档对象模型(DOM)。例如,在浏览器中运行的JavaScript脚本将无法工作。在所有。解决方案是在无头浏览器上运行JavaScript。幸运的是,有一个项目仍然活跃:Mozilla Firefox有一个无头模式。

https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode

$ /Applications/Firefox.app/Contents/MacOS/firefox -headless index.html
*** You are running in headless mode.

在Ubuntu上安装libjavascriptcoregtk-3.0-bin,并使用/usr/bin/jsc (manpage)。