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中文网其他相关文章!