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])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
