Home > database >  NESTJS error "ENOENT" breaking the API server
NESTJS error "ENOENT" breaking the API server

Time:09-20

I Have a route in my NESTJS Node API server to get files, however when there's no File specified on the path, I recieve the error :

Error: ENOENT: no such file or directory, open '(the path specified)'

After the error occurs my server stop working and I have to restart the process again with "nest start".

How do I catch this error, and return it to the request, instead of just breaking the API?

The code:

try {
  const file = createReadStream(join(process.cwd(), filesrc.path));

  res.set({
    "Content-Type": `${filesrc.type}`,
    "Content-Disposition": `attachment;filename="${filesrc.original_name}"`,
    "Content-Length":  filesrc.size
  })
  res.status(200);
  return new StreamableFile(file);
} catch (err) {
  throw new HttpException('test', 500)
}

Note: the "filesrc" is the variable that holds some file information.

CodePudding user response:

Two Solutions that I Found:

#1 (Recommended) as Jay McDoniel suggested, upgrade NestJS to latest version, version 9 fixes the issue.

#2 (If you can't upgrade your NestJs, my case) you can check if the file exists first using Node's fs 'existSync' function

 try {
  if (fs.existsSync(filesrc.path)) {
    const file = createReadStream(join(process.cwd(), filesrc.path));
    res.set({
      "Content-Type": `${filesrc.type}`,
      "Content-Disposition": `attachment;filename="${filesrc.original_name}"`,
      "Content-Length":  filesrc.size
    })
    res.status(200);
    return new StreamableFile(file);
  }
  else {
    throw new HttpException('File not found', HttpStatus.NOT_FOUND)
  }
} catch (err) {
  if (err.message) {
    throw new HttpException(err.message, err.status)
  }
  throw new HttpException(err, 500)
}

with this 'workaround' you can throw the error yourself and prevent the server from breaking.

  • Related