📜  Node.js script.createCachedData() 方法

📅  最后修改于: 2022-05-13 01:56:39.692000             🧑  作者: Mango

Node.js script.createCachedData() 方法

script.createCachedData() 方法是脚本模块的内置应用程序编程接口,用于创建可与脚本构造函数的cachedData选项一起使用的代码缓存。它可以在任何时间和任意次数调用。
句法:

script.createCachedData()

参数:此方法不接受任何参数。
返回值:返回缓冲区。
下面的例子说明了 Node.js 中script.createCachedData() 方法的使用:
示例 1:

javascript
// Node.js program to demonstrate the     
// script.createCachedData() method
  
// Including vm module
const vm = require("vm");
  
// Constructing script and defining a
// function add inside it
const script = new vm.Script(`
  
function add(a, b) {
  return a + b;
}
  
const x = add(1, 2);
`);
  
// Calling createCachedData without caching
// the variable x used above
const cacheWithoutx = script.createCachedData();
console.log(cacheWithoutx);


javascript
// Node.js program to demonstrate the     
// script.createCachedData() method
  
// Including vm module
const vm = require("vm");
  
// Constructing script and defining a
// function add inside it
const script = new vm.Script(`
  
function add(a, b) {
  return a + b;
}
  
const x = add(1, 2);
`);
  
// Calling runInThisContext method
script.runInThisContext();
  
// Calling createCachedData with caching
// the variable x used above
const cacheWithx = script.createCachedData();
console.log(cacheWithx);


输出:

示例 2:

javascript

// Node.js program to demonstrate the     
// script.createCachedData() method
  
// Including vm module
const vm = require("vm");
  
// Constructing script and defining a
// function add inside it
const script = new vm.Script(`
  
function add(a, b) {
  return a + b;
}
  
const x = add(1, 2);
`);
  
// Calling runInThisContext method
script.runInThisContext();
  
// Calling createCachedData with caching
// the variable x used above
const cacheWithx = script.createCachedData();
console.log(cacheWithx);

输出:

参考: https://nodejs.org/api/vm.html#vm_script_createcacheddata