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中文網其他相關文章!