乐闻世界logo
搜索文章和话题

What is the difference between res.send and res.write in express?

1个答案

1

In the Express framework, res.send and res.write are two methods used for handling HTTP responses, but they differ in functionality and use cases.

res.send

The res.send method is specific to the Express framework and is used for sending HTTP responses. This method is relatively high-level and highly flexible, as it automatically handles various data types and sets the correct Content-Type header. res.send can send strings, HTML, JSON objects, etc., and automatically ends the response (i.e., calls res.end()) after sending data.

Example:

Suppose we need to return a JSON object to the client; we can use res.send as follows:

javascript
app.get('/data', (req, res) => { res.send({ message: "Hello, world!" }); });

In this example, res.send automatically handles JSON serialization and sets the correct Content-Type header (application/json).

res.write

The res.write method is a lower-level method from Node.js's core HTTP module. It is primarily used for streaming write operations to the response. res.write requires manually calling res.end() to end the response. This approach is particularly useful when handling large data or sending data in batches, as it allows multiple writes to the response stream.

Example:

Suppose we need to send large amounts of data in batches; we can use res.write and res.end as follows:

javascript
app.get('/large-data', (req, res) => { res.write('Data block 1'); res.write('Data block 2'); // Other data writes... res.end('Final data block'); });

In this example, res.write is used to write multiple data blocks sequentially, and res.end sends the final data block and terminates the response.

Summary

In summary, res.send is a more advanced and convenient method, suitable for most common use cases, as it automatically handles data types and ends the response. Conversely, res.write provides greater control and is ideal for scenarios requiring batch processing or streaming data. In high-performance applications, using res.write correctly can improve response efficiency.

2024年8月2日 14:23 回复

你的答案