Node.js 中 Stream writable.writableLength 属性


writable.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
ode>> 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
ode>> 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 的原因。

更新于: 2021-05-20

170 次浏览

开启你的 职业

完成课程以获得认证

开始
广告