这是您读取整个文件内容的方法,如果成功完成,则启动一个Web服务器,该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
。
您甚至可以将image<img>
与数据URI源一起直接嵌入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>');