gpt4 book ai didi

javascript - 使用 Nodejs 提供图像

转载 作者:行者123 更新时间:2023-12-02 18:59:34 26 4
gpt4 key购买 nike

我有一个图像 pic.jpeg,我必须在浏览器上显示它。这是我编写的代码片段。

var mimeTypes = {
'.js' : 'text/javascript',
'.css' : 'text/css',
'.gif' : 'image/gif',
'.jpeg': 'image/jpeg',
'.html': 'text/html'
};

contenttype = mimeTypes[path.extname(req.url)];
pathname = "." + req.url;

var stream = fs.createReadStream(pathname);
stream.on('error', function(error) {
res.writeHead(500);
res.end();
return;
});
res.setHeader('Content-Type', contenttype);
res.writeHead(200);
stream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
util.pump(stream, res, function(error) {
//Only called when the res is closed or an error occurs
console.log("Error:");
res.end();
return;
});
});

上面的代码在大多数情况下都有效,并且图像显示正常,但有时图像会丢失。

最佳答案

您不应该通过node.js 提供静态文件。您应该考虑使用 Nginx 或类似的 Web 服务器来实现相同的目的。

或者,您可以使用connect模块来提供静态文件

var server = connect()
.use('/static', connect.static(__dirname + '/static'))
.use(router)
.listen(port);

创建一个名为static的新目录并将所有文件放入其中,这样您就可以通过/static/images/testimage.jpg访问它们

关于javascript - 使用 Nodejs 提供图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14937117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com