Phương thức writable.cork() ép buộc tất cả dữ liệu ghi tiếp theo được đệm trong bộ nhớ. Dữ liệu này chỉ được xả ra khi gọi writable.uncork() hoặc writable.end().
Cú pháp
cork()
writable.cork()
uncork()
writable.uncork()
Ví dụ 1: Chỉ dùng cork()
Tạo file cork.js:
node cork.js
const stream = require('stream');
const writable = new stream.Writable({
write: function(chunk, encoding, next) {
console.log(chunk.toString());
next();
}
});
// Ghi trước cork() - in ra ngay
writable.write('Hi - This data is printed');
// Bật cork()
writable.cork();
// Ghi sau cork() - bị đệm, KHÔNG in ra
writable.write('Welcome to TutorialsPoint!');
writable.write('SIMPLY LEARNING');
writable.write('This data will be corked in the memory');
Kết quả
Hi - This data is printed
Chỉ dữ liệu trước cork() được xử lý. Dữ liệu sau đó bị giữ trong bộ đệm.
Ví dụ 2: Sử dụng uncork() để xả bộ đệm
File uncork.js:
const stream = require('stream');
const writable = new stream.Writable({
write: function(chunk, encoding, next) {
console.log(chunk.toString());
next();
}
});
writable.write('Hi - This data is printed');
writable.cork();
writable.write('Welcome to TutorialsPoint!');
writable.write('SIMPLY LEARNING');
writable.write('This data will be corked in the memory');
// Xả bộ đệm
writable.uncork();
Kết quả
Hi - This data is printed Welcome to TutorialsPoint! SIMPLY LEARNING This data will be corked in the memory
Tất cả dữ liệu bị đệm sau cork() được in ra sau khi gọi uncork().
Lưu ý quan trọng
cork()/uncork()thường dùng để gom nhóm nhiều lần ghi nhỏ thành một lần ghi lớn, tối ưu hiệu suất I/O.- Gọi
uncork()nhiều lần không gây lỗi (lần thứ 2 trở đi không tác dụng). writable.end()cũng tự động xả bộ đệm.