在模块中启用V8中的和谐ES6function?

节点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)) 

我明白,这些不是生产就绪的function,并且正在开发中,但其中许多function已经足够好了。

有没有办法在运行时启用它们?

 "use strict"; "use harmony collections"; 

像上面的东西。 即使这些function不仅仅是模块级别的启用,也可以确保它们在模块内部启用,而不是假定它们已启用。

不,你不能。 事实上,如果你试图在同一个V8实例中隐藏这些标志的多个不同设置(披露:我实现了这些标志的大部分),那么在V8内部,有些事情可能会发生可怕的错误。

没有办法做到这一点,解释器读取模块的内容,然后validation它们,然后评估它们。 如果您将使用一些ES6特定的语法,那么validation将失败,代码将不会被评估。

你只能隔离ES6的语法文件,并将它们作为subprocess运行(有必要的选项),但我想这不是你想要做的。

以前的答案对于一个模块(隔离一个exec / child进程中的ES6文件)并不是一个坏主意,如果你能够处理它在一个subprocess中运行的想法。

最好的答案是,如果你是一个模块,logging你需要这些function,并在运行时testing它们,并保留一个有用的错误。 我自己也没弄清楚如何testing这个很好的(给我一个rest时间,我已经使用了3天的节点)

如果您正在编写应用程序,答案略有不同。 在我的情况下,我写的应用程序可能会使用这些function – 由于只能在shebang行中使用单个参数的限制,不能在运行时更改JS版本(其中当然,如上所述,完全有意义),而不想执行一个subprocess(我的服务器已经是multithreading) – 我不得不编写一个脚本来运行我的节点服务器,以便我的用户不必出了适当的节点命令行来运行我的应用程序(丑陋),如果我想要使用不止--harmony"use strict"; 我可以用脚本来做,因为它只是一个调用节点和我的应用程序的shell脚本。

build议使用#!/usr/bin/env node作为shebang(无论安装到哪里,都可以find节点),但是只能在shebang中使用一个参数,所以这不适用于--harmony (或任何其他参数)

当然 – 你总是可以运行node --harmony --use_strict --blah_blah yourScript.js ,但是如果你需要某些选项,你必须每次input它,因此build议使用shell脚本(由我!)。 我想你可以包含这个(或这样的)脚本与你的模块,并build议它用于执行使用你的模块的应用程序。

这与我用于我的服务器的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中指定,您可以硬编码节点的位置,并使用“使用严格”; 别名:

 #!/usr/bin/node --harmony "use strict";