node.js在覆盖图像时无法提供图像
node.js unable to serve image when it is being overwritten
我有一个node.js应用程序,它定期轮询图像并将它们存储到文件系统中。
问题是,当node.js覆盖图像时,无论谁在那一刻访问网站,都会看到到处都是空白图像(因为那一刻图像正在被覆盖)。
每当需要轮询图像时,这种情况只会发生几秒钟,但这很烦人。在我们覆盖图像时,是否仍然可以提供图像?
保存/覆盖图像的代码:
// This method saves a remote path into a file name.
// It will first check if the path has something to download
function saveRemoteImage(path, fileName)
{
isImagePathAvailable(path, function(isAvailable)
{
if(isAvailable)
{
console.log("image path %s is valid. download now...", path);
console.log("Downloading image file from %s -> %s", path, fileName);
var ws = fs.createWriteStream(fileName);
ws.on('error', function(err) { console.log("ERROR DOWNLOADIN IMAGE FILE: " + err); });
request(path).pipe(ws);
}
else
{
console.log("image path %s is invalid. do not download.");
}
});
}
提供图像的代码:
fs.exists(filePath, function(exists)
{
if (exists)
{
// serve file
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
readStream.pipe(res);
return;
}
我建议将新版本的图像写入一个临时文件:
var ws = fs.createWriteStream(fileName + '.tmp');
var temp = request(path).pipe(ws);
并在文件完全下载后将其重命名:
temp.on('finish', function() {
fs.rename(fileName + '.tmp', fileName);
});
我们使用'finish'
事件,当所有数据都已写入底层系统(即文件系统)时,就会触发该事件。
可能对更好
- 下载时提供旧版本的文件
- 将新文件下载到临时文件(例如
_fileName
) - 下载后重命名文件,从而重写原始文件
相关文章:
- 在Node.js中上传和检索图像
- 如何在Node.js中调整图像大小
- "回声“;Node.js中的图像
- 使用 Node.js 和 socket.io 和 fs 动态显示图像
- node.js在覆盖图像时无法提供图像
- 如何在Node.js中请求图像并输出图像
- 如何从Node中的图像url将图像上传到谷歌云存储
- node.js表示将外部图像推送到客户端
- base64字符串使用Node.JS被写为无效图像
- 如何使用node.js服务器显示图像
- node.js从http请求列表中将图像下载到服务器
- 如何使用Node.js显示从http请求到外部API的图像
- 是否可以使用node.js从powerpoint中提取幻灯片并将其保存为图像
- 使用node.js表达,不压缩jpeg图像
- Node.js-检测图像优化
- 更改JSON中图像标记的宽度通过Javascript返回(Node.JS)
- 用于编写用于使用 node.js 上传图像的筛选器列表的设计模式
- 将图像从 Xamarin C# 应用程序上传到 Node JS 服务器上的 Multer
- 上传的图像不会保存在 Node.js 的目标路径中
- 使用GraphicsMagick和Node.js将多个图像转换为多页pdf文件