Node.js | script.createCachedData () Метод

Опубликовано: 3 Августа, 2021

Метод script.createCachedData () - это встроенный интерфейс прикладного программирования модуля сценария, который используется для создания кэша кода, который можно использовать с параметром cachedData конструктора сценария. Его можно вызвать в любое время и любое количество раз.

Синтаксис:

 script.createCachedData ()

Параметры: этот метод не принимает никаких параметров.

Возвращаемое значение: возвращает буфер.

Примеры ниже иллюстрируют использование метода script.createCachedData () в Node.js:

Пример 1:




// 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 varibale x used above
const cacheWithoutx = script.createCachedData();
console.log(cacheWithoutx);

Выход:

<Буфер b5 03 de c0 8a f4 d4 f4 3f 00 00 00
ff 03 00 00 d5 a2 f5 b7 06 00 00 00 00 00 00 
00 28 02 00 00 аф 79 f4 0d a0 8c bf b8 00 00
00 80 20 0000 80 00 03 ...>

Пример 2:




// 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 varibale x used above
const cacheWithx = script.createCachedData();
console.log(cacheWithx);

Выход:

 <Буфер b5 03 de c0 8a f4 d4 f4 3f 00
00 00 и далее 03 00 00 d5 a2 f5 b7 06 00 00 00 00
00 00 00 00 03 00 00 03 67 df 75 6d 4c 36 07
00 00 00 80 20 0000 80 38 04 ...>

Ссылка: https://nodejs.org/api/vm.html#vm_script_createcacheddata