Node v0.10.20提供了许多关于和声的选项,
--harmony_typeof (enable harmony semantics for typeof)
--harmony_scoping (enable harmony block scoping)
--harmony_modules (enable harmony modules (implies block scoping)
--harmony_proxies (enable harmony proxies)
--harmony_collections (enable harmony collections (sets, maps, and weak maps))
--harmony (enable all harmony features (except typeof))我知道这些都不是可用于生产的特性,它们还在开发中,但其中许多已经足够好了。
有没有办法在运行时启用它们?
"use strict";
"use harmony collections";类似于上面的内容。即使这些功能不仅仅是模块级启用,最好确保它们在模块内部启用,而不是假设它们是启用的。
发布于 2013-10-19 00:04:01
不,你不能。事实上,如果你试图在同一个V8实例中偷偷引入这些标志的多个不同设置,那么在V8内部可能会出现严重的错误(透露:这些标志中的大多数都是我实现的)。
发布于 2013-10-18 17:04:18
没有办法做到这一点,解释器读取模块的内容,然后验证它们,然后评估它们。如果您将使用一些特定于ES6的语法,那么验证将会失败,并且代码将不会被评估。
您只能隔离ES6语法文件并将其作为子进程运行(使用必要的选项),但我猜这不是您想要的方式。
发布于 2013-12-05 16:36:42
对于一个模块(在执行/子进程中隔离ES6文件)来说,前面的答案并不是一个坏主意,前提是您可以处理它在子进程中运行的想法。
看起来最好的答案是,如果你是一个模块,记录下你需要的这些特性,并在运行时对它们进行测试,然后抛出一个有用的错误。我自己还没有想好如何很好地测试(让我休息一下,我已经使用node三天了)
如果你正在写一个应用程序,答案会略有不同。在我的例子中,我正在编写的应用程序可能会利用这些特性--由于只能在shebang行中使用单个参数的限制,不能在运行时更改JS版本(当然,如上所述,这是完全有意义的),我不想执行子进程(我的服务器已经是多线程的了)--我不得不写一个脚本来运行我的节点服务器,这样我的用户就不必找出正确的节点命令行来运行我的应用程序(丑陋的),如果我想使用比--harmony和"use strict";更多的东西,我可以使用脚本,因为它只是一个调用节点和我的应用程序的外壳脚本。
建议使用#!/usr/bin/env node作为shebang (它将为您找到节点,无论它安装到哪里)。但是,您只能在shebang中使用一个参数,因此这不适用于--harmony (或任何其他参数)
当然-你总是可以运行node --harmony --use_strict --blah_blah yourScript.js,但是如果你需要某些选项,你必须每次都输入它,因此建议使用shell脚本(由我!)。我想你可以在你的模块中包含这个(或类似的)脚本,并建议在执行使用你的模块的应用程序时使用它。
这是一个类似于我为我的服务器使用的shell脚本的实现,它将找到节点并使用您需要的任何参数运行您的脚本:
#!/bin/bash
if [ "$myScript" == "" ]; then
myScript="./src/myNodeServer.js"
fi
if [ "$myNodeParameters" == "" ]; then
myNodeParameters="--harmony --use_strict"
fi
if [ "$myNode" = "" ]; then
myNode=`which node`
fi
if [ "$myNode" = "" ]; then
echo node was not found! this app requires nodeJS to be installed in order to run.
echo if you have nodeJS installed but is not found, please make sure the 'which'
echo command is available. alternatively, you can forcibly specify the location of
echo node with the $myNode environment variable, or editing this file.
else
echo Yay! node binary was found at $myNode
fi
if [ "$1" = "start" ]; then
echo you asked to start..
echo calling $myNode $myParameters $myScript $2
$myNode $myParameters $myScript $2
exit
elif [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo you asked for help..
echo usage:
echo $0 start [script.js] [parameters for script]
echo parameters for node and node location can be
echo set with the \$myParameters and \$myNode env
echo variables (or edit the top of this file).
exit
else
echo no valid command specified - use $0 --help to see help.
fi 值得注意的是,如果您只想使用和声和严格,而不能在shebang中同时指定两者,则可以硬编码节点的位置并使用"use strict";别名:
#!/usr/bin/node --harmony
"use strict";https://stackoverflow.com/questions/19437241
复制相似问题