Virtual machine environment (sandbox)
For example: when testing cases, you can use the sandbox, a clean environment, to execute
Under normal circumstances, the internal operation is string logic, how to make a string run?
1. When using eval, the variables under the current scope will be taken by default, which is an unclean environment
const a = 100;
eval("console.log('a---->', a)");
2. Use new Function to create a sandbox environment and let the string execute
const b = 200;
let fn = new Function("c", "d", "e", "console.log('b---->', b)");
console.log(fn.toString());
fn();
ejs module rendering
npm install ejs
Create a new template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<%=name%>
</div>
<div>
<%=age%>
</div>
<ul>
<%arr.forEach(item=> {%>
<li>
<%=item%>
</li>
<%})%>
</ul>
</body>
</html>
and then use the template
const ejs = require("ejs");
const path = require("path");
ejs.renderFile(
path.resolve(__dirname, "../file/template.html"),
{
name: "kaimo", age: "313", arr: [1, 2, 3] },
(err, data) => {
console.log(data);
}
);