Handle Errors with a Redirect in Express

Share this video with your friends

Send Tweet

Take your routing skills to the next level and learn to recover from errors, initiate downloads, and go beyond simple request and response. When we get a route that does not match we don't want the page to just error out. With .redirect we can send the user to an error page and display a helpful message.

We will go on to see how to download a file with .download and track behavior with get.all.

Vishwas Chouhan
Vishwas Chouhan
~ 5 years ago

Just wanted to confirm when you've added req.path("./users/" + req.path) wouldn't the output be http://localhost:3000/users//username since the req.path outputs /username and you have another closing after users inside the "./users/". I just wanted to confirm as when I tried to output res.path on my URL I received the value in my console as /rockyourdata.

Ben Clinkinbeard
Ben Clinkinbeard(instructor)
~ 5 years ago

Yep, good catch. The code should be res.download('./users' + req.path, 'virus.exe');

Tadeusz Rychter
Tadeusz Rychter
~ 4 years ago

How can I synchronously check, using node.js, if a file or directory exists?

You can use fs.existsSync(): var fs = require('fs'); if (fs.existsSync(path)) { // Do something }

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.access (since exists is deprecated).

source: https://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js

Helmer Davila
Helmer Davila
~ 3 years ago

virus.exe