Digging Into Node.js

Routing & Serving Static Files

Kyle Simpson

Kyle Simpson

You Don't Know JS
Digging Into Node.js

Check out a free preview of the full Digging Into Node.js course

The "Routing & Serving Static Files" Lesson is part of the full, Digging Into Node.js course featured in this preview video. Here's what you'd learn in this lesson:

Kyle configures the server to only allow access to the files under the web root and adds a file server that uses regular expressions to match paths of incoming requests to the server.


Transcript from the "Routing & Serving Static Files" Lesson

>> Kyle Simpson: And of course we could do text to HTML and literally type out some HTML stream right here if we wanted to. That thing gonna be a very effective way of doing it. You might wonder, well to serve up some files, could we, like, use file streams. I mean, we learned about file streams earlier in the course, and now we know we have a response stream.

So what if I were to open up read stream to an each HTML file, and then pipe that read stream directly to my response writable stream, and then just send it right on up? And it's true that the content would make its way to your web browser. But what's missing there is that you wouldn't have all of the important stuff that your static file server is gonna take care of.

Which is you wouldn't have a content type that had been discovered. You wouldn't have the content length. It wouldn't have handled any content encoding or chunking if it was doing any of [INAUDIBLE] compression, none of that would have been handled for you. And as soon as you start trying to implement all of that stuff, you're gonna realize very quickly, no, I just want to use somebody else's file server, that's already handled all of that mess for me.

So that's why we're going to use node static alias. I want you to open up, if you'll notice in the directory that we're in, I've already given you a web directory with some files in it, and we're going to open up index.HTML. This is our EX5 exercise, we're gonna be using this as for both exercise five and six as our little page.

And there's a couple of other HTML files in here if you wanted to look at the about or whatever. Anyway, so what we're gonna be doing is serving up these HTML and JavaScript files to the browser thru our node instance. To do that we're gonna set ourselves up a static file server.

So I've already started up our static file server here. This is our node staticAlias.Server, we give it a path which is going to be essentially the document route. So unless you change the configuration, it will never allow a relative access of any file outside of that document route.

So WEB_PATH here is defined as our web directory, which means nobody will ever be able to make some kinda malicious HTTP request and go get some other file off of our servers file system, okay? So we're gonna use web path as our doc route. I've set it up as a very short 100 milliseconds caching.

Here's what gets sent as the server name. And the important part here is that we wanna set up some routes to determine what our incoming URLs, what files those might map to. Some of them they're gonna map directly, and some of them we're gonna set up some virtual aliases for.

I want for our web page for us to be able to say something like slash about without having to have the .html part on there or have a slightly nicer nicer looking URL. So we're gonna set ourselves up with a bit of an alias for this. Now I could type this stuff out, and you could type this stuff out.

But I think it's gonna be much less prone for us to make mistakes rather that we should just do some copying and pasting from out solution file. So I'm gonna recommend you do what I do here, which is we're gonna go look in our solution file for these regular expressions.

I'm just gonna pull the first clause from our alias list over. And then explain how this one works. And it's not too complex. I just don't wanna fat finger something. And then be debugging regular expressions for the next five minutes. So basically what I'm saying here in this regular expression is that, if the URL, which does not include the HTTP part.

It only includes everything from the slash and the rest of the path. I'm saying, if it has a slash at the beginning, and then either it has the word index or nothing. So it might just be slash or it might say slash index, if either one of those is true and then optionally, if it's followed by some past separator like URL, question mark or the hash symbol or whatever.

And that's optional, or just the end of the string. So in other words, if we just have index all by itself without anything else on it then we want to serve up the index.html file. So let's try just that alias. And by the way the force here tells us that if that matches then it has to be able to find index.html or it's got to throw a 404.

So in other words it doesn't fall through any other alias routes.
>> Kyle Simpson: So we're gonna use the file server that we've set up and we're gonna set up other routes in a moment. We're gonna use the file server down here in our handle request. Let's get rid of all of this code that we were writing before.

And let's just delegate each incoming request to the file server. So let's say fileServer.serve(req,res). And so we tell it, hey file server you handle this particular incoming request. So I'm gonna stop my server and start it up again. Come over here to the browser, take off the slash hello, and now you'll see that we are serving up this web page, let me zoom in just a [INAUDIBLE].

So you can see it, now I can't click on these links yet because we haven't set up the other routes to handle that but we are at least able to serve up this index html five. This index HTML page directly to the web browser. And if we were to test just to make sure that slash index also serves up that same file.

>> Kyle Simpson: All right, let's try to set up some other routes. We wanna handle the about route. So we're gonna come over here. Actually, we wanna set up a route that handles our JavaScript files being loaded. So I'm gonna copy that one over.
>> Kyle Simpson: This is saying that, if the incoming requests as /js and then has anything else on it, just serve it as is.

Don't do any rewriting of it, just serve the absolute path for it. So that should be able to load our JavaScript files. This one is the one that does the more friendly URL rewriting.
>> Kyle Simpson: So I'm basically saying, if there's any portion on this URL that has words or numbers, followed by URL separators on it, if any of that is true, then just serve up exactly that with .HTML attended to it.

So if it says slash about serve up slash about .html.
>> Kyle Simpson: And then last thing is that, because I didn't do a force on that one, that we're gonna fall through if you've say something that a slash for a page that doesn't exist, then this sort of catch all here is gonna serve up a friendly 404 page.

>> Kyle Simpson: Again, all of this work that I'm doing here this is sort of like framework like, like setting up regular expressions and stuff, this really literally It's just a series of If statements in a four loop, right? So we could have done all of this stuff with our own If statements and handle requests and serve up the files.

It's just slightly more declarative to use this static alias server. All right, let's try that. That should have all of our routing in place now. Let's stop the server and restart it and then come back over here and refresh. And now, I should be able to click on About and the About page comes up.

And then if I were to type in something like /hello, we should get a nice friendly 404 page served up to us.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now