script.createCachedData() Method in Node.js


The script.createCachedData() method is used for creating a code cache that will be used along with the cachedData option of the script constructor. This cachedData can be called multiple number of times without latency. This method is an inbuilt programming interface from the 'script' module.

Syntax

script.createCachedData()

Parameters

Since it only caches the data. It does not require any specific inputs from the user. It only returns the cached buffer.

Example

Create a file with name – createCachedData.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node createCachedData.js

createCachedData.js

// Node.js program to demonstrate the flow of script.createCachedData() method

// Importing the vm module
const vm = require("vm");

// Defining the script as constant and usng the below function
// to create the cached data for the difference of two numbers.
const script = new vm.Script(`
   function add(a, b) {
      return a - b;
   }
   const x = add(2, 1);
`);

//Creating the cached data without caching the variable
const cacheWithoutx = script.createCachedData();
console.log(cacheWithoutx);

Output

C:\home
ode>> node createCachedData.js <Buffer b5 03 de c0 8a f4 d4 f4 3d 00 00 00 ff 03 00 00 d5 a2 f5 b7 06 00 00 00 00 00 00 00 28 02 00 00 8f 87 4d e3 59 55 98 f9 00 00 00 80 20 00 00 80 00 03 ... >

Example

Let's take a look at one more example.

// Node.js program to demonstrate the flow of script.createCachedData() method

// Importing the vm module
const vm = require("vm");

// Defining the script as constant and usng the below function
// to create the cached data for the difference of two numbers.
const script = new vm.Script(`
   function add(a, b) {
      return a - b;
   }
   const x = add(2, 1);
`);

// Calling the runInThisContext from script module
script.runInThisContext();

//Creating the cached data along with caching the variable
const cacheWithx = script.createCachedData();
console.log(cacheWithx);

Output

C:\home
ode>> node createCachedData.js <Buffer b5 03 de c0 8a f4 d4 f4 3d 00 00 00 ff 03 00 00 d5 a2 f5 b7 06 00 00 00 00 00 00 00 00 03 00 00 15 80 fd 5d 69 21 3a a9 00 00 00 80 20 00 00 80 38 04 ... >

Updated on: 20-May-2021

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements