Node.js 中的流 writable.writableLength 属性
该writable.writableLength属性用于显示队列中准备写入的字节数或对象数。这用于根据highWaterMark的状态检查数据。
语法
writeable.writableLength
示例1
创建一个具有名称的文件-writableLength.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示-
node writableLength.js
//演示writable.writableLength方法的程序 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'); //调用cork()函数 writable.cork(); //再次写入一些数据 writable.write('Welcome to nhooo !'); writable.write('SIMPLY LEARNING '); writable.write('This data will be corked in the memory'); //打印队列数据的长度 console.log(writable.writableLength);输出结果
C:\home\node>> node writableLength.js Hi - This data will not be counted 81
在控制台中计算并打印被塞住并在缓冲区队列内的数据。
示例
让我们再看一个例子。
//演示writable.cork()方法的程序 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'); //调用cork()函数 writable.cork(); //再次写入一些数据 writable.write('Welcome to nhooo !'); writable.write('SIMPLY LEARNING '); writable.write('This data will be corked in the memory'); //打印队列数据的长度 console.log(writable.writableLength); //从缓冲内存中刷新数据 writable.uncork() console.log(writable.writableLength);输出结果
C:\home\node>> node writableLength.js Hi - This data will not be counted 81 Welcome to nhooo ! SIMPLY LEARNING This data will be corked in the memory 0
由于现在数据已经在uncork().队列不会保存任何数据,这就是返回长度为0的原因。