📜  Node.js http.ClientRequest.writableEnded API(1)

📅  最后修改于: 2023-12-03 15:03:13.224000             🧑  作者: Mango

Node.js http.ClientRequest.writableEnded API

The http.ClientRequest.writableEnded API is a property that represents whether the request has ended or not. When it returns true, it means that the request has been sent and the connection has been closed. When it returns false, it means that the request has not yet been sent or the server has not yet responded.

Syntax
const writableEnded = request.writableEnded
Description

The writableEnded property is a boolean value that indicates whether the http.ClientRequest has finished writing data to the socket. If an error occurs before the data is completely written, the client will receive an error event with the error message.

You can use this property to detect if it's safe to write more data to the request. For example, in a scenario where you are writing a stream of data to the request, you might want to wait until the writableEnded property returns true before writing any more data.

Example
const http = require('http')

const options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
}

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', (d) => {
    process.stdout.write(d)
  })
})

req.on('error', (error) => {
  console.error(error)
})

req.write(postData)

if (req.writableEnded) {
  console.log('Request has been sent')
}
else {
  console.log('Request not sent yet')
}

req.end()

In the example above, we are creating an HTTP request to upload data to a server. We first create the request by calling http.request() and passing in options such as the hostname, port number, path, method, and headers. Then, we write some data to the request using the req.write() method.

Next, we check if the req.writableEnded property returns true. Since the req.write() method was used before this check, it is likely that the request has already been sent. If so, we log a message saying that the request has been sent. If not, we log a message saying that the request has not yet been sent.

Finally, we end the request by calling req.end(). This will send any remaining data and close the connection.