检测成功打开读取流 [英] Detecting successful read stream open

查看:84
本文介绍了检测成功打开读取流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Express.js的静态服务中间件实现缓存,该缓存的工作方式如下—当请求到来时,中间件首先尝试从文件系统提供文件,如果没有,则从上游获取文件并将其存储在文件中系统。

I'm implementing cache for static serving middleware for Express.js, which works as follows — when request comes, middleware first tries to serve file from filesystem, and if there is none, file is fetched from upstream and stored in file system.

问题是我不知道如何正确检测缓存命中事件。

Problem is I don't know how to properly detect "cache hit" event.

staticMiddleware = function(req, res, next) {
    // try to read file from fs
    filename = urlToFilename(req.url);
    stream = fs.createReadStream(filename);

    // cache miss - file not found
    stream.on('error', function() {
        console.log('miss ' + req.url);

        // get file from upstream, store it into fs and serve as response
        stream = fetchFromUpstream(url);
        stream.pipe(fs.createWriteStream(filename));
        stream.pipe(res);
    });

    // cache hit - file is being read
    I_DONT_KNOW_WHAT_TO_PUT_HERE(function() {
        console.log('hit ' + req.url);

        stream.pipe(res);
    });
}

因此,基本上,我如何检测成功的文件读取?如果我听数据事件,我想我会错过第一块数据。如果我只是 pipe()进行响应,则响应流会因错误而关闭,并且无法为获取的数据提供服务,并且这种方法确实缺乏灵活性。我想知道是否有办法监听诸如 fdcreated open 之类的事件,或者是否有回送数据的方法?已经有 data 事件,因此它将在下一个 data 事件中重新发送。

So, basically, how can I detect succesful file reading? If I listen to 'data' event, I guess I miss first chunk of data. If I just pipe() it to response, response stream gets closed on error, and I can't serve it with fetched data, and this approach really lacks flexibility. I wonder if there is way to listen for event like fdcreated or opened or similar, or way to push back data I've got in data event, so it will be resent in next data event.

推荐答案

方法 createReadStream 返回一个ReadableStream,它也有一个 open 。您可以为 open 事件添加事件处理程序,以便您知道资源何时处于在管道之前有效:

Method createReadStream returns a ReadableStream which also an event open. You can add an event handler for the open event so you will know when the resource is valid before piping:

stream.on('open', function() {
    console.log('hit ' + req.url);
    stream.pipe(res);
});

这篇关于检测成功打开读取流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆