首页 > web前端 > js教程 > 正文

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

WBOY
发布: 2023-09-16 22:53:08
转载
1332 人浏览过

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

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

语法

cork()

writeable.cork()
登录后复制

开塞()

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:\homeode>> node cork.js
Hi - This data is printed
登录后复制

只有在 cork() 方法之间写入的数据才会被打印,而其余数据将被塞入缓冲存储器中。下面的示例展示了如何从缓冲区内存中解锁上述数据。

示例

让我们再看一个有关如何 uncork() 的示例 - 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:\homeode>> node uncork.js
Hi - This data is printed
Welcome to TutorialsPoint !
SIMPLY LEARNING
This data will be corked in the memory
登录后复制

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

以上是Node.js 中的 Stream writable.cork() 和 uncork() 方法的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!