Join Alexander Zanfir for an in-depth discussion in this video Serving static files with Express, part of Up and Running with Node.js.
- When creating a web application, you can think of it as having a division between two responsibilities. You can either host static content or dynamic content. Static content can be things like HTML files for websites or images, videos, etc. Dynamic content, on the other hand, is served through a web API or sometimes it is used to serve a dynamic webpage where the view is pre-rendered on the server. In our case, we'll look at serving a simple HTML file for static files, and then we will create a web API to show how we can serve dynamic content.
So let's begin by serving some static files with Express.js. The first thing we'll do is create our exercise file, and we'll call this express-static-demo.js. One thing to keep in mind is Express does not come with Node, and so we'll need to install it using mpm. So let's do that now. Let's bring up the console or terminal and we'll use mpm install express. Now let's go back to our editor and take a look under Node modules to see if Express is there.
We'll refresh the file tree since it is not yet showing up, and there it is. So now let's begin by requiring it into a variable we'll call express, and then we'll set reference to a variable called app from an instance of express. And then to get the Express server started and listening for requests, we'll type in app.listen, and we can pass in a port of maybe 3000.
Now we'll save that, and we'll run it. And if we open our browser and go over to localhost with port 3000, we can see we're getting a response, but we're not actually getting anything and that's because we haven't yet served anything. So now let's serve some static content with Express. We'll begin by using app.use, and then what we'll do is we'll create an HTML file and we'll call it index.html so that it's served by default, and we'll just type in hello.
And we can close that. And in order to serve that file, we'll use express.static, and we'll pass in the directory through underscore underscore D-I-R name which will give us the project directory, and it will have the index.html as the default file it serves. So let's save that and run it again. Now let's go back to our browser and see what we get. We can refresh, and we see that we have our hello.
- Installing Node.js
- Writing modules and packages
- Reading and writing files
- Working with frameworks: Express, Sails, and Koa
- Generating promises
- Working with generator functions