惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
腾讯CDC
M
MIT News - Artificial intelligence
Y
Y Combinator Blog
L
LangChain Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
IT之家
IT之家
A
About on SuperTechFans
H
Help Net Security

轶哥博客

blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog
blog
2021-03-04 · via 轶哥博客

vm模块允许在V8虚拟机上下文中编译和运行代码。但是不是安全机制,如果有沙箱(sandbox)需求,可以考虑https://github.com/patriksimek/vm2

在VM环境中使用ECMAScript modules,即在VM环境中可以用import代替require引入某个模块,避免Cannot use import statement outside a module错误,也可以用export代替module.exports

我的使用场景:

通过Node.js在VM环境使用ECMAScript modules之目的,是为了构建一个虚拟环境(可控的上下文内容)动态执行一些代码,方便在复杂系统中构建小型脚本动态的快速验证一些想法。

https://github.com/yi-ge/api-proxy这个小项目中也有用到vm模块。

实现方法

vm.png

const vm = require('vm')

require = require("esm")(module)

vm.runInNewContext(`require("./main.js")`, {
  console,
  module,
  require
});

借助了esm开源模块(https://github.com/standard-things/esm),此时就可以在main.js中运行类似下面这样的代码了:

import fs from 'fs'

const a = fs.readFileSync('./main.ts', 'utf-8')
console.log(a)

其它

使用ems本质上还是转换为CommonJS,和使用babel进行转换本质上是一样的。

可以通过vm.Module实现更低级的ECMAScript modules接口运行在VM环境。

如果在package.json中定义了"type": "module",上述方法是无效的。因为requiremodule是未定义的。需要采用其它方法。