0

I just started learning Node.js and Express, and I'm currently trying to build a static file server. My question is: How do I prevent node from crashing every time the user inserts a wrong path? Here's my code:

var express=require('express')
var fs=require('fs')
var app=express()
var server=app.listen(3000, listening)
console.log('Server Started on Port 3000')

function listening(){
    console.log('Listening...')
}

app.use(express.static('website'))

app.get('/search/:page', goTo)


function goTo(req, res){
    var data=req.params
    fs.createReadStream('./website/'+data.page+'.html').pipe(res)
}

Thank you!

1 Answer 1

4

With try-catch your app will try to open the specified path. If it fails, your app will send an error instead of crashing.

Try this:

function goTo(req, res) {
    var data = req.params;
    try{
        fs.createReadStream('./website/'+data.page+'.html').pipe(res);
    } catch(err) {
        res.send(err);
    }
}

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

You should explain what you've done, since he's only just started out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.