Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức script.createCachedData() trong Node.js


Phương thức script.createCachedData() dùng để tạo bộ nhớ đệm mã (code cache) sử dụng cùng với tùy chọn cachedData của constructor script. Dữ liệu cachedData có thể gọi nhiều lần mà không gây độ trễ. Đây là giao diện lập trình nội bộ từ module 'script' (thực tế là module vm).

Cú pháp

script.createCachedData()

Tham số

Vì chỉ lưu đệm dữ liệu, không cần đầu vào cụ thể. Chỉ trả về buffer đã đệm.

Ví dụ

Tạo file createCachedData.js và sao chép mã. Chạy lệnh:

node createCachedData.js

createCachedData.js

// Chương trình Node.js minh họa script.createCachedData()
// Import module vm
const vm = require("vm");

// Định nghĩa script và tạo cached data cho phép trừ
const script = new vm.Script(`
    function add(a, b) {
        return a - b;
    }
    const x = add(2, 1);
`);

// Tạo cached data không cache biến
const cacheWithoutx = script.createCachedData();
console.log(cacheWithoutx);

Kết quả

C:\home\node>> node createCachedData.js

Ví dụ 2

Ví dụ chạy script trước rồi tạo cached data kèm biến.

// Chương trình Node.js minh họa script.createCachedData()
// Import module vm
const vm = require("vm");

const script = new vm.Script(`
    function add(a, b) {
        return a - b;
    }
    const x = add(2, 1);
`);

// Chạy script trong context hiện tại
script.runInThisContext();

// Tạo cached data kèm cache biến
const cacheWithx = script.createCachedData();
console.log(cacheWithx);

Kết quả

C:\home\node>> node createCachedData.js