expressjs / expressjs/multer

callback not firing when custom storage engine finishes handling file.

Open
#1,026 4 comments 8 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
12.1k
Forks
1.1k
Avg merge
8d 2h
Merged PRs (30d)
21

Description

I have started writing a custom storage engine for a cloud storage provider. The file upload works, but when the upload is finished and the cb is invoked, express.js does not move to the next step on the route, causing the request to that route to hang indefinitely. There are no errors on the server and I can't see anything using debug, but the console.log before the cb() works, the console.log in the routes file doesn't.

This is the code for the CustomStorageEngine. The uploadFile function is just a couple of fetch calls to the cloud provider and some error handling. I am new to node/express, is the callback being called in a promise an issue? If I pass an error to the callback it behaves normally.
```
class CustomStorageEngine implements multer.StorageEngine {
private nameFn: nameFnType;
private siteURL: string;

constructor(opts: Options) {
this.nameFn = opts.nameFn || defaultNameFn;
this.siteURL = opts.siteUrl
}

_handleFile = (
req: Request,
file: Express.Multer.File,
cb: (error?: any, info?: CustomFileResult) => void
): void => {

const fileName = this.nameFn(req, file);

uploadFile(fileName, file, this.siteURL)
.then((asset: CloudAsset) => {
console.log(asset); // this fires

cb(null, { id: asset.id, name: asset.name, url: asset.url })
})
.catch((error) => {
cb(error)
})
};

_removeFile = (
_req: Request,
file: Express.Multer.File & { name: string },
cb: (error: Error | null) => void
): void => {
cb(null)
};
}
```
```
export default (opts: Options) => {
return new CustomStorageEngine(opts);
};
```
This is the code for the route.
```
const router = Router();

const uploader = multer({
storage: StorageEngine(
{
siteUrl: config.siteUrl
}
)
})

router.post('/asset', uploader.single('file'), async (req, res) => {
console.log(req.file) // this never fires
res.status(200).json({
"id": (req.file as CustomFileResult).id,
"url": (req.file as CustomFileResult).url,
"name": (req.file as CustomFileResult).name,
"physical_file_path": (req.file as CustomFileResult).physicalFilePath
});
});

export default router;
```

Any help would be greatly appreciated

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.