writable.cork()方法用于強(qiáng)制所有寫入的數(shù)據(jù)緩沖在內(nèi)存中。只有在調(diào)用stream.uncork()或stream.end()方法后,緩沖數(shù)據(jù)才會(huì)從緩沖存儲(chǔ)器中刪除。
語(yǔ)法
cork()
writeable.cork()
登錄后復(fù)制
開(kāi)塞()
writeable.uncork()
登錄后復(fù)制
參數(shù)
因?yàn)樗彌_寫入的數(shù)據(jù)。唯一需要的參數(shù)將是可寫數(shù)據(jù)。
示例
創(chuàng)建一個(gè)名為 cork.js 的文件并復(fù)制以下代碼片段。創(chuàng)建文件后,使用以下命令運(yùn)行此代碼,如下例所示 –
node cork.js
登錄后復(fù)制
cork.js
?現(xiàn)場(chǎng)演示
// 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');
登錄后復(fù)制
輸出
C:\homeode>> node cork.js Hi - This data is printed
登錄后復(fù)制
只有在 cork() 方法之間寫入的數(shù)據(jù)才會(huì)被打印,而其余數(shù)據(jù)將被塞入緩沖存儲(chǔ)器中。下面的示例展示了如何從緩沖區(qū)內(nèi)存中解鎖上述數(shù)據(jù)。
示例
讓我們?cè)倏匆粋€(gè)有關(guān)如何 uncork() 的示例 – uncork.js
?現(xiàn)場(chǎng)演示
// 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()
登錄后復(fù)制
輸出
C:\homeode>> node uncork.js Hi - This data is printed Welcome to TutorialsPoint ! SIMPLY LEARNING This data will be corked in the memory
登錄后復(fù)制
使用 uncork() 方法刷新緩沖內(nèi)存后,就會(huì)顯示上面示例中的完整數(shù)據(jù)。
以上就是Node.js 中的 Stream writable.cork() 和 uncork() 方法的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!