writable.write(chunk[, encoding][, callback])
版本 | 變化 |
---|---|
v8.0.0 |
|
v6.0.0 | 將 |
v0.9.4 | 添加於:v0.9.4 |
參數
chunk
<string> | <Buffer> | <Uint8Array> | <any> 可選數據寫入。對於不在對象模式下運行的流,chunk
必須是字符串,Buffer
或Uint8Array
。對於對象模式流,chunk
可以是除null
之外的任何 JavaScript 值。encoding
<string> | <null> 編碼,如果chunk
是字符串。 默認:'utf8'
callback
<Function> 刷新此數據塊時的回調。- 返回: <boolean>
false
如果流希望調用代碼在繼續寫入其他數據之前等待發出'drain'
事件;否則true
。
writable.write()
方法將一些數據寫入流,並在數據完全處理後調用提供的callback
。如果發生錯誤,將調用 callback
,並將錯誤作為其第一個參數。 callback
在'error'
發出之前被異步調用。
如果內部緩衝區小於在承認 chunk
後創建流時配置的 highWaterMark
,則返回值為 true
。如果返回 false
,則應停止進一步嘗試將數據寫入流,直到發出
事件。'drain'
當流沒有耗盡時,對 write()
的調用將緩衝 chunk
並返回 false。一旦所有當前緩衝的塊被耗盡(操作係統接受交付),將發出 'drain'
事件。一旦 write()
返回 false,在發出 'drain'
事件之前不要寫入更多塊。在允許在未耗盡的流上調用 write()
時,Node.js 將緩衝所有寫入的塊,直到達到最大內存使用量,此時它將無條件中止。甚至在它中止之前,高內存使用會導致垃圾Collector性能差和 RSS 高(通常不會將其釋放回係統,即使在不再需要內存之後也是如此)。由於如果遠程對等方不讀取數據,TCP 套接字可能永遠不會耗盡,因此寫入不耗盡的套接字可能會導致遠程可利用的漏洞。
在流未耗盡時寫入數據對於
尤其成問題,因為默認情況下 Transform
Transform
流會暫停,直到它們通過管道傳輸或添加 'data'
或 'readable'
事件處理程序。
如果要寫入的數據可以按需生成或獲取,建議將邏輯封裝成
並使用Readable
。但是,如果首選調用 stream.pipe()
write()
,則可以使用
事件來尊重背壓並避免內存問題:'drain'
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
對象模式下的 Writable
流將始終忽略 encoding
參數。
相關用法
- Node.js stream.Writable.uncork()用法及代碼示例
- Node.js stream.Writable.end([chunk[, encoding]][, callback])用法及代碼示例
- Node.js stream.Writable.destroyed用法及代碼示例
- Node.js stream.Writable.destroy([error])用法及代碼示例
- Node.js stream.Readable.take(limit[, options])用法及代碼示例
- Node.js stream.Readable.pipe(destination[, options])用法及代碼示例
- Node.js stream.Readable.setEncoding(encoding)用法及代碼示例
- Node.js stream.Readable.some(fn[, options])用法及代碼示例
- Node.js stream.Readable.map(fn[, options])用法及代碼示例
- Node.js stream.Readable.toArray([options])用法及代碼示例
- Node.js stream.Readable.isPaused()用法及代碼示例
- Node.js stream.Readable.forEach(fn[, options])用法及代碼示例
- Node.js stream.Readable.every(fn[, options])用法及代碼示例
- Node.js stream.finished()用法及代碼示例
- Node.js stream.Readable.from()用法及代碼示例
- Node.js stream.Readable.read([size])用法及代碼示例
- Node.js stream.Readable.flatMap(fn[, options])用法及代碼示例
- Node.js stream.finished(stream[, options], callback)用法及代碼示例
- Node.js stream.Readable.unshift(chunk[, encoding])用法及代碼示例
- Node.js stream.Readable.filter(fn[, options])用法及代碼示例
- Node.js stream.Readable.asIndexedPairs([options])用法及代碼示例
- Node.js stream.Readable.drop(limit[, options])用法及代碼示例
- Node.js stream.Readable.resume()用法及代碼示例
- Node.js stream.Readable.reduce(fn[, initial[, options]])用法及代碼示例
- Node.js stream.addAbortSignal(signal, stream)用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 stream.Writable.write(chunk[, encoding][, callback])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。