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

Thuộc tính writable.writableLength trong Node.js


Thuộc tính writable.writableLength trả về số lượng byte (hoặc số đối tượng nếu ở object mode) hiện đang nằm trong hàng đợi ghi (write queue) chờ được xử lý. Giá trị này hữu ích để kiểm tra trạng thái bộ đệm so với highWaterMark.

Cú pháp

writable.writableLength

Ví dụ 1: Kiểm tra độ dài hàng đợi khi dùng cork()

Tạo file writableLength.js:

node writableLength.js
const stream = require('stream');

const writable = new stream.Writable({
  write: function(chunk, encoding, next) {
    console.log(chunk.toString());
    next();
  }
});

// Ghi dữ liệu trước khi cork - sẽ được ghi ngay
writable.write('Hi - This data will not be counted');

// Bật cork() để đệm dữ liệu
writable.cork();

// Ghi thêm dữ liệu - sẽ bị đệm trong bộ nhớ
writable.write('Welcome to TutorialsPoint!');
writable.write('SIMPLY LEARNING');
writable.write('This data will be corked in the memory');

// Kiểm tra writableLength
console.log(writable.writableLength); // 81 (số byte của 3 chuỗi trên)

Kết quả

Hi - This data will not be counted
81

Chỉ dữ liệu được ghi sau cork() mới được tính vào writableLength.

Ví dụ 2: Kiểm tra sau khi uncork()

const stream = require('stream');

const writable = new stream.Writable({
  write: function(chunk, encoding, next) {
    console.log(chunk.toString());
    next();
  }
});

writable.write('Hi - This data will not be counted');
writable.cork();
writable.write('Welcome to TutorialsPoint!');
writable.write('SIMPLY LEARNING');
writable.write('This data will be corked in the memory');

console.log(writable.writableLength); // 81

// Xả bộ đệm
writable.uncork();

console.log(writable.writableLength); // 0

Kết quả

Hi - This data will not be counted
81
Welcome to TutorialsPoint!
SIMPLY LEARNING
This data will be corked in the memory
0

Sau khi gọi uncork(), dữ liệu được xả khỏi bộ đệm, do đó writableLength trả về 0.