how to handle 404 redirect if non www is redirected to www

I'm using Node.js and I want to render 404 page if route doesn't exist but the problem is I also redirected my webpage from non-www to www. Below is the code I used for non-www to www redirect.

app.all(/.*/, function(req, res, next) {
    var host = req.header("host");
    if (host.match(/^www\..*/i))
        res.redirect(301, "http://www." + host);

I also want a 404 error handling with this. I read many post regarding this but none of them help me. How to do it.

Backend technology used is Node.js