简体   繁体   中英

Catch error on serveFile function from node-static

Seems that the documentation does not provide this information.

When using serveFile how can I check if the file served does exist?

fileServer.serveFile('/error.html', 500, {}, request, response);

In other words, how can I check if the file was served successfully?

Seems that serveFile function doesn't accept a callback function. Or am I wrong?

It appears the serveFile returns a "promise" (although it's not a promise, it's an instance of EventEmitter ) so you can listen for the error event on that (it will fire when the file doesn't exist):

Server.prototype.serveFile = function (pathname, status, headers, req, res) {
    var that = this;
    var promise = new(events.EventEmitter);

    pathname = this.resolve(pathname);

    fs.stat(pathname, function (e, stat) {
        if (e) {
            return promise.emit('error', e);
        }
        that.respond(null, status, headers, [pathname], stat, req, res, function (status, headers) {
            that.finish(status, headers, req, res, promise);
        });
    });
    return promise;
};

If the file is served successfully, the finish method is called, and the same "promise" object is passed in to it. It will emit a success event:

Server.prototype.finish = function (status, headers, req, res, promise, callback) {
    // ...

    if (!status || status >= 400) {
        // ...
    } else {
        // ...
        promise.emit('success', result);
    }
};

So, you can do something like this:

var promise = fileServer.serveFile('/error.html', 500, {}, request, response);
promise.on("success", function () {
    // It worked!
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM