Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

gen-uniqueid

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

gen-uniqueid

`vm-node` 是一款Node端代码沙箱,在`vm2`的基础上,额外解决了代码死循环、各类异常捕获等问题,沙箱内能`共享`所处运行环境的node_module中已安装的包

  • 0.0.1
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

简介

vm-node 是一款Node端代码沙箱,在vm2的基础上,额外解决了代码死循环、各类异常捕获等问题,沙箱内能共享所处运行环境的node_module中已安装的包

案例演示

const {createVM} = require('vm-node');
const vm = createVM({timeout: 30000})
// 或
const vm = createVM() // 默认超时时长:10s

// 正常使用1
vm.run('hooks.onFinished({name: "andy"})').then((data) => {
  console.log(data) // {name: "andy"}
})
// 正常使用2
vm.run(`
  const axios = require('axios');
  const wrapper = async () => {
    try {
      const res = await axios.get("http://localhost:8080/api/test");
      // 将结果传递至外部,并标记执行结束
      hooks.onFinished(res.data)
    } catch(e) {
      logger.log('出错了')
      logger.log(e.message)
    }
  }
  wrapper()
`).then(data => {
  console.log('沙箱执行结果是', data)
})

// 捕获内部错误1
vm.run('logger.log(a)').catch(e => {
  console.log('外部收到错误', e)
})
// 捕获内部错误2
vm.run(`Promise.reject('这是Promise错误信息')`).catch(e => {
  console.log('外部收到错误', e)
})
// 捕获内部错误3
vm.run('process.exit()').catch(e => {
  console.log('外部收到错误', e)
})

createVM

  • timeout: 沙箱代码超时配置
  • openLog: 是否开启log开关,开启则会将中间日志全部输出

内置全局变量

  • logger: 打印日志相关,涵盖了 log、info、warn、error
  • hooks:沙箱运行的生命周期钩子
    • onFinished: 沙箱执行结束,可以将内部数据传递至外部
    • onError:沙箱执行出错,会直接结束程序

Tips

  • 沙箱中的代码如果使用了外部依赖,请确保沙箱运行的外部环境有此依赖
  • 如果需要将沙箱中运行的结果传递至外部,请调用 hooks.onFinished 方法进行传递

FAQs

Package last updated on 17 Feb 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc