response.write(chunk[, encoding][, callback])
chunk<string> | <Buffer> | <Uint8Array>encoding<string> 默认值:'utf8'callback<Function>- 返回:<boolean>
如果调用此方法而 response.writeHead() 尚未被调用,它将切换到隐式头模式并刷新隐式头。
【If this method is called and response.writeHead() has not been called,
it will switch to implicit header mode and flush the implicit headers.】
这会发送响应主体的一部分。此方法可以被多次调用以提供主体的连续部分。
【This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.】
如果在 createServer 中将 rejectNonStandardBodyWrites 设置为 true,那么当请求方法或响应状态不支持内容时,不允许写入主体。如果尝试在 HEAD 请求或作为 204 或 304 响应的一部分写入主体,将会抛出带有 ERR_HTTP_BODY_NOT_ALLOWED 代码的同步 Error。
【If rejectNonStandardBodyWrites is set to true in createServer
then writing to the body is not allowed when the request method or response
status do not support content. If an attempt is made to write to the body for a
HEAD request or as part of a 204 or 304response, a synchronous Error
with the code ERR_HTTP_BODY_NOT_ALLOWED is thrown.】
chunk 可以是字符串或缓冲区。如果 chunk 是字符串,第二个参数指定如何将其编码为字节流。当这段数据被刷新时,会调用 callback。
这是原始的 HTTP 正文,与可能使用的更高级的多部分正文编码无关。
【This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.】
第一次调用 response.write() 时,它会将缓冲的头信息和响应体的第一块发送给客户端。第二次调用 response.write() 时,Node.js 假设数据将以流的方式发送,并会单独发送新数据。也就是说,响应会缓冲到响应体的第一块为止。
【The first time response.write() is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time response.write() is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.】
如果所有数据都成功刷新到内核缓冲区,则返回 true。如果所有或部分数据被排队在用户内存中,则返回 false。当缓冲区再次空闲时,会触发 'drain' 事件。
【Returns true if the entire data was flushed successfully to the kernel
buffer. Returns false if all or part of the data was queued in user memory.
'drain' will be emitted when the buffer is free again.】