我有用于从目录读取图像并将其发送到index.html的代码。
我试图用fs.createReadStream替换fs.readFile,但是我不知道如何实现它,因为我找不到很好的例子。
这是我得到的(index.js)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
http.listen(3000, function () {
console.log('listening on *:3000');
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
io.on('connection', function (socket) {
fs.readFile(__dirname + '/public/images/image.png', function (err, buf){
socket.emit('image', { image: true, buffer: buf.toString('base64') });
});
});
index.html
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="200" height="100">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io();
var ctx = document.getElementById('canvas').getContext('2d');
socket.on("image", function (info) {
if (info.image) {
var img = new Image();
img.src = 'data:image/jpeg;base64,' + info.buffer;
ctx.drawImage(img, 0, 0);
}
});
</script>
</body >
</html >
最佳答案
以下方法仅使用核心模块,并从stream.Readable
返回的fs.createReadStream()
实例读取块,并将这些块作为Buffer
返回。如果您不打算将数据块流回去,那么这并不是什么好方法。您将把文件保存在内存中的Buffer
中,因此,这只是大小合理的文件的一个很好的解决方案。
io.on('connection', function (socket) {
fileToBuffer(__dirname + '/public/images/image.png', (err, imageBuffer) => {
if (err) {
socket.emit('error', err)
} else {
socket.emit('image', { image: true, buffer: imageBuffer.toString('base64') });
}
});
});
const fileToBuffer = (filename, cb) => {
let readStream = fs.createReadStream(filename);
let chunks = [];
// Handle any errors while reading
readStream.on('error', err => {
// handle error
// File could not be read
return cb(err);
});
// Listen for data
readStream.on('data', chunk => {
chunks.push(chunk);
});
// File is done being read
readStream.on('close', () => {
// Create a buffer of the image from the stream
return cb(null, Buffer.concat(chunks));
});
}
HTTP响应流示例
由于
HTTP
内置在协议(protocol)中,因此几乎总是一个更好的主意,因为它可以直接将pipe()
文件流直接发送到响应,因此您无需一次将数据全部加载到内存中。这是一个非常基本的示例,没有花哨的地方,只是演示了如何将
pipe()
编码为stream.Readable
。该示例使用Express,但使用Node.js Core API中的http.ServerResponse
或http
的方式完全相同。const express = require('express');
const fs = require('fs');
const server = express();
const port = process.env.PORT || 1337;
server.get ('/image', (req, res) => {
let readStream = fs.createReadStream(__dirname + '/public/images/image.png')
// When the stream is done being read, end the response
readStream.on('close', () => {
res.end()
})
// Stream chunks to response
readStream.pipe(res)
});
server.listen(port, () => {
console.log(`Listening on ${port}`);
});