0
点赞
收藏
分享

微信扫一扫

python 使用node_vm2执行js

跟着Damon写代码 2022-03-25 阅读 191

有时候,一些js需要调用,之前都是用nodejs比较多,但是有些js会验证是否使用的是node
就比如某头条的加密。为了能本地调用扣下来的js,这里就不能用nodejs或者execjs,
需要用到vm2

步骤:
1、下载vm2

pip install node_vm2 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

加载方式如下:

大多数 API 都绑定到vm2。

简单评估:

from node_vm2 import eval

print(eval("['foo', 'bar'].join()"))

使用虚拟机:

from node_vm2 import VM

with VM() as vm:
   vm.run("""
      var sum = 0, i;
      for (i = 0; i < 10; i++) sum += i;
   """)
   print(vm.run("sum"))

使用 NodeVM:

from node_vm2 import NodeVM

js = """exports.greet = name => console.log(`Hello ${name}!`);"""

with NodeVM.code(js) as module:
   module.call_member("greet", "John")

可以使用 Promise 执行异步任务:

from datetime import datetime
from node_vm2 import NodeVM

js = """
exports.test = () => {
   return new Promise(resolve => {
      setTimeout(() => {
         resolve("hello")
      }, 3000);
   });
};
"""
with NodeVM.code(js) as module:
   print(datetime.now())
   print(module.call_member("test"))
   print(datetime.now())

如果您希望允许 VM 使您的服务器崩溃(例如process.exit()),您应该在单独的服务器中创建 VM,这样它就不会影响其他 VM:

from node_vm2 import VMServer, VM

with VMServer() as server:
   with VM(server=server) as vm:
      # now the vm is created in a new server
      print(vm.run("1 + 2 + 3"))

API 参考

http://node-vm2.readthedocs.io/

项目地址:https://github.com/eight04/node_vm2

举报

相关推荐

0 条评论