Stream writable.cork() 和 uncork() 方法在 Node.js 中


writable.cork() 方法用于强制将所有写入的数据缓冲在存储器中。只有当调用 stream.uncork() 或 stream.end() 方法后,此缓冲数据才会从缓冲存储器中删除。

语法

cork()

writeable.cork()

uncork()

writeable.uncork()

参数

由于它会缓冲写入的数据。需要的唯一参数将是可写数据。

示例

创建一个名为 cork.js 的文件并复制下面的代码片段。创建文件后,使用以下命令运行此代码,如下例所示 −

node cork.js

cork.js

 在线演示

// 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
writable.write('Hi - This data is printed');

// 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');

输出

C:\home
ode>> node cork.js Hi - This data is printed

只有使用 cork() 方法写入的数据才会被打印,而其余数据将被缓冲在缓冲存储器中。下面的示例显示了如何从缓冲存储器中取消缓冲以上数据。

示例

让我们看另一个关于如何进行取消缓冲的示例 - uncork.js

 在线演示

// 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
writable.write('Hi - This data is printed');

// 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');

// Flushing the data from buffered memory
writable.uncork()

输出

C:\home
ode>> node uncork.js Hi - This data is printed Welcome to TutorialsPoint ! SIMPLY LEARNING This data will be corked in the memory

上述示例中的完整数据在使用 uncork() 方法刷新缓冲内存后显示。

更新时间: 20-5-2021

553 人次浏览

Kickstart Your Career

完成课程以获得认证

开始学习
广告