คุณสมบัติ write.writableLength ใช้สำหรับแสดงจำนวนไบต์หรืออ็อบเจ็กต์ที่อยู่ในคิวที่พร้อมจะเขียน ใช้สำหรับตรวจสอบข้อมูลตามสถานะจาก highWaterMark
ไวยากรณ์
writeable.writableLength
ตัวอย่างที่ 1
สร้างไฟล์ที่มีชื่อ – writableLength.js และคัดลอกข้อมูลโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ให้ใช้คำสั่งต่อไปนี้เพื่อเรียกใช้โค้ดนี้ดังแสดงในตัวอย่างด้านล่าง −
node writableLength.js
// Program to demonstrate writable.writableLength 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 - Not in the buffer queue
writable.write('Hi - This data will not be counted');
// 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');
// Printing the length of the queue data
console.log(writable.writableLength); ผลลัพธ์
C:\home\node>> node writableLength.js Hi - This data will not be counted 81
ข้อมูลที่ถูกปิดและอยู่ในคิวบัฟเฟอร์จะถูกนับและพิมพ์ในคอนโซล
ตัวอย่าง
ลองดูอีกตัวอย่างหนึ่ง
// 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 - Not in the buffer queue
writable.write('Hi - This data will not be counted');
// 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');
// Printing the length of the queue data
console.log(writable.writableLength);
// Flushing the data from buffered memory
writable.uncork()
console.log(writable.writableLength); ผลลัพธ์
C:\home\node>> node writableLength.js Hi - This data will not be counted 81 Welcome to TutorialsPoint ! SIMPLY LEARNING This data will be corked in the memory 0
เนื่องจากตอนนี้ข้อมูลถูกล้างหลังจาก uncork() คิวจะไม่เก็บข้อมูลใด ๆ ซึ่งเป็นสาเหตุที่ความยาวส่งคืนเป็น 0