Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

script.createCachedData() เมธอดใน Node.js


เมธอด script.createCachedData() ใช้สำหรับสร้างแคชโค้ดที่จะใช้ร่วมกับตัวเลือก cachedData ของตัวสร้างสคริปต์ cachedData นี้สามารถเรียกได้หลายครั้งโดยไม่มีเวลาแฝง เมธอดนี้เป็นอินเทอร์เฟซการเขียนโปรแกรม inbuilt จากโมดูล 'สคริปต์'

ไวยากรณ์

script.createCachedData()

พารามิเตอร์

เนื่องจากมันแคชข้อมูลเท่านั้น ไม่ต้องการอินพุตเฉพาะจากผู้ใช้ มันคืนค่าบัฟเฟอร์แคชเท่านั้น

ตัวอย่าง

สร้างไฟล์ที่มีชื่อ – createCachedData.js และคัดลอกข้อมูลโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ให้ใช้คำสั่งต่อไปนี้เพื่อเรียกใช้โค้ดนี้ดังแสดงในตัวอย่างด้านล่าง −

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);

ผลลัพธ์

C:\home\node>> 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 ... >

ตัวอย่าง

ลองดูอีกตัวอย่างหนึ่ง

// 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);

ผลลัพธ์

C:\home\node>> 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 ... >