[英]Return image using API - Pure NodeJS (no Express)
I am trying to return an image when a user connects to the server ip address, in short, create an API that returns an image.我试图在用户连接到服务器 ip 地址时返回图像,简而言之,创建一个返回图像的 API。
I had found this solution that worked however now I don't know why it doesn't work.我找到了这个可行的解决方案,但是现在我不知道为什么它不起作用。
I don't want to use Express or similar.我不想使用 Express 或类似的。
UPDATE更新
Without res.end()
it works, but I don't understand why.没有
res.end()
它可以工作,但我不明白为什么。
import http from 'http';
import mime from 'mime';
import fs from 'fs';
const hostname = '127.0.0.1';
const port = 8000;
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': mime.getType('./tmp/screenshot.png') });
fs.createReadStream('./tmp/screenshot.png').pipe(res);
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
in:在:
fs.createReadStream('./tmp/screenshot.png').pipe(res);
you already add a pipe
to send data between the server and the client and after finishing sending data, it automatically triggers the end()
event.您已经添加了一个
pipe
在服务器和客户端之间发送数据,并且在完成发送数据后,它会自动触发end()
事件。 if you don't want this behavior.如果你不想要这种行为。 just do this
就这样做
fs.createReadStream('./tmp/screenshot.png').pipe(res, {end:false});
I hope it's help you:)我希望它对你有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.