Enable Harmony Proxies in nodejs

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 21:59:15

Invoking node with node --harmony-proxies should do the trick.

Pros: proxies are a very powerful feature when you really need them.

Cons: proxies are a much too powerful feature when you don't need them (which should be most of the time). Also, the implementation should still be regarded experimental.

As for documentation, all there really is atm is the Harmony wiki, in particular this page, which reflects the current implementation of proxies in V8 (and thus node):

http://wiki.ecmascript.org/doku.php?id=harmony:proxies

i recommend harmony-reflect, which makes it easy to e.g. set up get/set traps:

UPDATE careful, below is CoffeeScript

require 'harmony-reflect'

handler =

  get: ( target, name ) ->
    console.log 'get' name
    return target[ name ]

  set: ( target, name, value ) ->
    console.log 'set' name
    target[ '%is-clean' ] = no if value isnt target[ name ]
    if value is undefined then delete target[ name ]
    else                       target[ name ] = value
    return value

clean = ( x ) ->
  x[ '%is-clean' ] = yes
  return x

p = Proxy {}, handler
p[ 'a' ] = 1
p[ 'b' ] = undefined
console.log p[ 'a' ], p[ 'b' ]
console.log "c" of p, p[ 'c' ]
console.log p
clean p
p[ 'a' ] = 1
console.log p
p[ 'a' ] = 42
console.log p

the above is the inceptive code to do 'transparent object persistence' in JavaScript. using harmony-reflect, it becomes trivial to make it so that all get and set actions on an object get intercepted—in this demo, we set an %is-clean attribute so we can test whether object members have been changed, and we also delete members that have been set to undefined.

You can use pimped-proxy which a lightweight implementation of proxies, making declaration easier and ES5 compatible. Unlike the native Proxy, it can only proxy properties known at creation time.

https://github.com/Boulangerie/pimped-proxy

Proxy is now available natively in Node versions >= 6.

Harmony Proxies won't work all that well for nodejs because they're effectively synchronous type function calls. That is, you can't implement a proxy method that's async.

See this GitHub repository for examples: https://github.com/mschwartz/SilkJS-Harmony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!