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() 方法的詳細內容,更多請關注www.92cms.cn其它相關文章!