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() 方法刷新缓冲内存后显示。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP