如何解决Node.js-在ETIMEDOUT中请求大量数据结果
我确实请求api端点,该端点包含大量数据,需要一些时间来获取。我的请求有时成功,但有时会出现ETIMEDOUT错误。我尝试增加请求的超时时间,但这不能解决我的问题。有没有办法分块加载数据或增加服务器超时?
解决方法
将模块http
与http.request()
结合使用,您可以按照以下说明设置超时时间:How to set a timeout on a http.request() in Node?
请注意,您可以在回调的块res.on('data',...)
事件中加载数据,例如:
const req = http.request(options,(res) => {
res.on('data',(chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end',() => {
console.log('No more data in response.');
});
});
req.end();
代码和更多详细信息,位于:https://nodejs.org/api/http.html#http_http_request_url_options_callback
,是的,有一种方法可以分块发送响应。您需要使用Node.js流。
下面是一个例子。
http.createServer(function(req,res) {
// The filename is simple the local directory and tacks on the requested url
var filename = __dirname+req.url;
// This line opens the file as a readable stream
var readStream = fs.createReadStream(filename);
// This will wait until we know the readable stream is actually valid before piping
readStream.on('open',function () {
// This just pipes the read stream to the response object (which goes to the client)
**readStream.pipe(res);**
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error',function(err) {
res.end(err);
});
}).listen(8080);
上面的代码来自Node.js文档。
关注“ readStream.pipe(res);”部分
res正在与读取文件一起连续发送。如果文件很大,它仍然可以缓慢且连续地发送给客户端。
查看文档,
https://nodejs.org/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream/
类似地,您还可以允许客户端流式传输大型视频文件,比如说750MB。只是,处理视频还有更多复杂性。
,正如人们已经提到的,使用Streams。
假设客户端从我们的服务器请求一个大文件(以下代码中的file.txt
)。使用流,我们以块的形式发送此文件,而不是将其缓冲在内存中。服务器不占用大量RAM,客户端可以立即获得响应,每个人都很高兴。
const fs = require("fs");
const http = require("http");
const server = http.createServer();
const port = 8000;
server.on("request",(req,res) => {
const src = fs.createReadStream("./file.txt"); // file.txt is some big file
src.pipe(res);
fs.readFile("./file.txt",(err,data) => {
if (err) throw err;
res.end(data);
});
});
server.listen(port,() => { `Server is listening on http://localhost:${port}` });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。