我一直在寻找一个如何读取jpeg图像,然后显示图像的例子.

var http = require('http'), fs = require('fs');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});

fs.readFile('image.jpg', function (err, data) {
  if (err) throw err;
  res.write(data);
});

res.end();
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

try 了以下代码,但我认为编码需要设置为缓冲区.使用控制台.记录输出数据的"对象".

推荐答案

以下是如何读取整个文件内容,如果成功,则启动一个Web服务器,该服务器显示JPG图像以响应每个请求:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

注意,服务器是通过"readFile"回调函数启动的,响应头有Content-Type: image/jpeg个.

[Edit]甚至可以使用<img>data URI source将图像直接嵌入HTML页面.例如:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

Node.js相关问答推荐

Sveltekit停靠的应用程序找不到从Build导入的包

在内存中加载安全密钥安全吗?还是每次都从文件中读取?

MongooseError[MissingSchemaError]:尚未为模型注册架构

将 null 推入管道后,node.js 可写完成未发出

Cloudflare 522 错误 - javascript 客户端连接到 node 服务器

如何解决 npm install react-select failure with error : An unknown git error occurred, git@github.com :Permission denied (publickey)

更新文档数组中的文档 Mongoose

使用 firebase 函数 api 运行套接字(相同的端口创建问题)

类 WebSwapCGLLayer 在 Mac OS X /System 和 node_modules 中都实现了

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

将 myproject/.npmrc 与注册表一起使用

如何将`yarn.lock`与`package.json`同步?

无法获取 CSS 文件

如何在 MongoDB 中查询引用的对象?

Passport 的 req.isAuthenticated 总是返回 false,即使我硬编码 done(null, true)

npm install - javascript堆内存不足

如何在 NodeJS 中拆分和修改字符串?

从 node.js 连接到 mongodb 时出现 ECONNREFUSED 错误

Mongoose:模式与模型?

Mongoose - 验证邮箱语法