xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

how to run a string code in js All In One

how to run a string code in js All In One

How to Execute JavaScript Code Stored in a String

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-04-14
 * @modified
 *
 * @description
 * @augments
 * @example
 * @link https://www.typescriptlang.org/docs/handbook/enums.html
 * @link https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums
 *
 */

const log = console.log;

enum Direction {
  Up,
  Down,
  Left,
  Right
}

/*

"use strict";
var Direction;
(function (Direction) {
  Direction[Direction["Up"] = 0] = "Up";
  Direction[Direction["Down"] = 1] = "Down";
  Direction[Direction["Left"] = 2] = "Left";
  Direction[Direction["Right"] = 3] = "Right";
})(Direction || (Direction = {}));

*/

const map = new Map();
// Map(0) { size: 0 }
map.set('Up', 0);
// Map(1) { 'Up' => 0 }
map.set('Down', 1);
// Map(2) { 'Up' => 0, 'Down' => 1 }
map.set('Left', 3);
// Map(3) { 'Up' => 0, 'Down' => 1, 'Left' => 3 }
map.set('Right', 4);
// Map(4) { 'Up' => 0, 'Down' => 1, 'Left' => 3, 'Right' => 4 }

// AST parser
const enumGenerator = (name: string, map: Map<string, number>) => {
  // interface Map<K, V>
  // Generic type 'Map<K, V>' requires 2 type argument(s).ts(2314)//
  console.log('map', map);
  const dict = [];
  for (const [key, index] of map.entries()) {
    // Direction[Direction["Up"] = 0] = "Up";
    console.log('key, index', key, index);
    dict.push(`${name}[${name}["${key}"] = ${index}] = "${key}";\n`);
  }
  const code = `
    "use strict";
    var ${name};
    (function (${name}) {
      ${dict.join('')}
    })(${name} || (${name} = {}));
  `;
  console.log(`code =`, code);
  return code;
}

const code = enumGenerator('Direction', map);

log('code =', code);
// 执行 js string code
setTimeout(code, 0);


export {
  enumGenerator,
};

setTimeout ✅


const code = `
    "use strict";
    var Direction;
    (function (Direction) {
      Direction[Direction["Up"] = 0] = "Up";
      Direction[Direction["Down"] = 1] = "Down";
      Direction[Direction["Left"] = 3] = "Left";
      Direction[Direction["Right"] = 4] = "Right";
    })(Direction || (Direction = {}));
`;

setTimeout(code, 0);

console.log('Direction', Direction);
// Direction {0: 'Up', 1: 'Down', 3: 'Left', 4: 'Right', Up: 0, Down: 1, Left: 3, Right: 4} ✅

script


const code = `
    "use strict";
    var Direction;
    (function (Direction) {
      Direction[Direction["Up"] = 0] = "Up";
      Direction[Direction["Down"] = 1] = "Down";
      Direction[Direction["Left"] = 3] = "Left";
      Direction[Direction["Right"] = 4] = "Right";
    })(Direction || (Direction = {}));
`;


const script = document.createElement("script");
script.text = code;
document.body.appendChild(script);

console.log('Direction', Direction);
// Direction {0: 'Up', 1: 'Down', 3: 'Left', 4: 'Right', Up: 0, Down: 1, Left: 3, Right: 4} ✅


const code = `
    "use strict";
    var Direction;
    (function (Direction) {
      Direction[Direction["Up"] = 0] = "Up";
      Direction[Direction["Down"] = 1] = "Down";
      Direction[Direction["Left"] = 3] = "Left";
      Direction[Direction["Right"] = 4] = "Right";
    })(Direction || (Direction = {}));
`;

// 不执行
document.body.insertAdjacentHTML('beforeend', `<script>${code}</script>`);

console.log('Direction', Direction);
// Uncaught ReferenceError: Direction is not defined ❌

Function Constructor


const code = `
    "use strict";
    var Direction;
    (function (Direction) {
      Direction[Direction["Up"] = 0] = "Up";
      Direction[Direction["Down"] = 1] = "Down";
      Direction[Direction["Left"] = 3] = "Left";
      Direction[Direction["Right"] = 4] = "Right";
    })(Direction || (Direction = {}));
`;

const func = new Function(code);
func();

console.log('Direction', Direction);
// Uncaught ReferenceError: Direction is not defined ❌

eval() function ❌

eval(string);

console.log(eval('2 + 2'));
// 4
const code = `
    "use strict";
    var Direction;
    (function (Direction) {
      Direction[Direction["Up"] = 0] = "Up";
      Direction[Direction["Down"] = 1] = "Down";
      Direction[Direction["Left"] = 3] = "Left";
      Direction[Direction["Right"] = 4] = "Right";
    })(Direction || (Direction = {}));
`;

eval(code);

console.log('Direction', Direction);
// Uncaught ReferenceError: Direction is not defined ❌

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

node.js vm


const script = new vm.Script(`
function add(a, b) {
  return a + b;
}

const x = add(1, 2);
`);

const cacheWithoutX = script.createCachedData();

script.runInThisContext();

const cacheWithX = script.createCachedData();

https://nodejs.org/api/vm.html#class-vmscript

refs

https://stackoverflow.com/questions/939326/execute-javascript-code-stored-as-a-string

https://thewebdev.info/2021/04/22/how-to-execute-javascript-code-stored-in-a-string/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-14 22:44  xgqfrms  阅读(25)  评论(2编辑  收藏  举报