Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adapter.rm calls cb twice when fd is not found #39

Open
evson-custodio opened this issue Jul 9, 2019 · 1 comment
Open

adapter.rm calls cb twice when fd is not found #39

evson-custodio opened this issue Jul 9, 2019 · 1 comment

Comments

@evson-custodio
Copy link

Hi everyone, I have encountered a small problem in your code, take a look at this excerpt from the rm function:

adapter.rm = (fd, cb) => {
    const errorHandler = (err, client) => {
        if (client) client.close();
        if (cb) cb(err);
    }

    client(options.uri, options.mongoOptions, (err, client) => {
        if (err) {
            errorHandler(err, client);
        }

        bucket(client.db(), options.bucketOptions).delete(fd, (err) => errorHandler(err, client));
        if (cb) cb();
    });
}

I need a little attention on these two lines:

bucket(client.db(), options.bucketOptions).delete(fd, (err) => errorHandler(err, client));
if (cb) cb();
  1. The second line is always executed if cb exists.
  2. The first line performs the deletion, but if no file is found with the given fd, errorHandler is called, this function in turn calls cb passing an err, if cb exists.

The problem encountered is that cb is called twice, if cb exists and no file is found with fd passed to the function, thus meeting the two rules mentioned above. So for a cb like this:

fileAdapter.rm(req.param('fd'), (err) => {
    if (err) {
        res.send(err.message);
    }
    else {
        res.send('File deleted');
    }
});

res.send is called twice, one containing the err and again without err generating the following error:

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Forgiveness for English, text translated by Google Translate.

@dmedina2015
Copy link

dmedina2015 commented Mar 11, 2021

In fact, call back function in bucket.delete() is always called, even if fd matches to a file in GridFS. If you debug you will see it being called with err = null (because there is no error).

I forked the repo and fix it. PR #44 waiting for review and approval. @mikermcneil @willhuang85

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants