The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Handle Errors with a Redirect in Express

Handle Errors with a Redirect in Express

6:48
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`.
Watch this lesson now
Avatar
egghead.io

Take your routing skills to the next level and learn to recover from errors, initiate downloads, and go beyond simple request and response.

Avatar
Vishwas

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.

Avatar
Ben

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

In reply to Vishwas
Avatar
Tadeusz

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

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?