Computer >> Máy Tính >  >> Lập trình >> Javascript

Luồng phương thức writeable.cork () và unork () trong Node.js

Phương thức writeable.cork () được sử dụng để buộc tất cả dữ liệu đã ghi vào bộ nhớ đệm. Dữ liệu được đệm này sẽ chỉ bị xóa khỏi bộ nhớ đệm sau khi phương thức stream.uncork () hoặc stream.end () được gọi.

Cú pháp

nút chai ()

writeable.cork()

unork ()

writeable.uncork()

Tham số

Vì nó đệm dữ liệu đã viết. Chỉ tham số cần thiết mới là dữ liệu có thể ghi.

Ví dụ

Tạo một tệp có tên - cork.js và sao chép đoạn mã bên dưới. Sau khi tạo tệp, sử dụng lệnh sau để chạy mã này như được hiển thị trong ví dụ bên dưới -

node cork.js

cork.js

// Program to demonstrate writable.cork() method
const stream = require('stream');

// Creating a data stream with writable
const writable = new stream.Writable({
   // Writing the data from stream
   write: function(chunk, encoding, next) {
      // Converting the data chunk to be displayed
      console.log(chunk.toString());
      next();
   }
});

// Writing data
writable.write('Hi - This data is printed');

// Calling the cork() function
writable.cork();

// Again writing some data
writable.write('Welcome to TutorialsPoint !');
writable.write('SIMPLY LEARNING ');
writable.write('This data will be corked in the memory');

Đầu ra

C:\home\node>> node cork.js
Hi - This data is printed

Chỉ dữ liệu được ghi giữa phương thức cork () sẽ được in trong khi dữ liệu còn lại sẽ được ghi vào bộ nhớ đệm. Ví dụ dưới đây cho thấy cách mở khóa dữ liệu trên khỏi bộ nhớ đệm.

Ví dụ

Hãy xem thêm một ví dụ về cách hủy liên kết () - uncork.js

// Program to demonstrate writable.cork() method
const stream = require('stream');

// Creating a data stream with writable
const writable = new stream.Writable({
   // Writing the data from stream
   write: function(chunk, encoding, next) {
      // Converting the data chunk to be displayed
      console.log(chunk.toString());
      next();
   }
});

// Writing data
writable.write('Hi - This data is printed');

// Calling the cork() function
writable.cork();

// Again writing some data
writable.write('Welcome to TutorialsPoint !');
writable.write('SIMPLY LEARNING ');
writable.write('This data will be corked in the memory');

// Flushing the data from buffered memory
writable.uncork()

Đầu ra

C:\home\node>> node uncork.js
Hi - This data is printed
Welcome to TutorialsPoint !
SIMPLY LEARNING
This data will be corked in the memory

Dữ liệu đầy đủ từ ví dụ trên được hiển thị khi bộ nhớ đệm được xóa bằng phương thức unork ().