node.js在覆盖图像时无法提供图像

node.js unable to serve image when it is being overwritten

本文关键字:图像 node 覆盖 覆盖图 js      更新时间:2023-09-26

我有一个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
  • 下载后重命名文件,从而重写原始文件