Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js无法在覆盖图像时为其提供服务_Javascript_Image_Node.js - Fatal编程技术网

Javascript node.js无法在覆盖图像时为其提供服务

Javascript node.js无法在覆盖图像时为其提供服务,javascript,image,node.js,Javascript,Image,Node.js,我有一个node.js应用程序,它定期轮询图像并将它们存储到文件系统中 问题是,当node.js覆盖图像时,此时访问网站的任何人都会看到到处都是空白图像(因为此时图像正在被覆盖) 每当需要轮询图像时,这种情况只会发生几秒钟,但这很烦人。在我们覆盖图像时,是否仍然能够为图像提供服务 保存/覆盖图像的代码: // This method saves a remote path into a file name. // It will first check if the path has somet

我有一个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;
        } 

也许最好是

  • 下载时提供旧版本的文件
  • 将新文件下载到临时文件(例如,
    \u fileName
  • 下载后重命名文件,从而重写原始文件
我建议将图像的新版本写入临时文件:

var ws = fs.createWriteStream(fileName + '.tmp');
var temp = request(path).pipe(ws);         
当文件完全下载时:

temp.on('finish', function() {
    fs.rename(fileName + '.tmp', fileName);
});

我们使用,当所有数据都写入底层系统(即文件系统)时会触发。

您好,抱歉。我不能完成比赛,我只能完成比赛。看起来使用close事件也可以正确重命名。使用关闭事件是否正确?
close
事件由可读流(即您示例中的请求流)发出,而
finish
事件由可写流(即
ws
)发出。你确定你听对了吗?嗨,保罗,我听了你的代码。我正在收听临时流。我想您正在使用节点0.8.x,其中确实是可写流,并且没有发出
finish
事件。在这种特定情况下,是的,您应该监听
close
事件,因为文档说明它是在底层文件描述符关闭时发出的。请注意,当您切换到Node>=0.10时,您必须收听
finish