Serving static files with Express

- When creating a web application, you can thinkof it as having a division between two responsibilities.You can either host static content or dynamic content.Static content can be things like HTML filesfor websites or images, videos, etc.Dynamic content, on the other hand, is servedthrough a web API or sometimes it is usedto serve a dynamic webpage where the viewis pre-rendered on the server.In our case, we'll look at serving a simple HTML filefor static files, and then we will create a web APIto 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 comewith Node, and so we'll need to install it using mpm.So let's do that now.Let's bring up the console or terminaland we'll use mpm install express.Now let's go back to our editor and take a lookunder Node modules to see if Express is there.

We'll refresh the file tree since itis not yet showing up, and there it is.So now let's begin by requiring it into a variablewe'll call express,and then we'll set reference to a variable called appfrom an instance of express.And then to get the Express server startedand 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 overto localhost with port 3000,we can see we're getting a response,but we're not actually getting anythingand 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 iswe'll create an HTML file and we'll call it index.htmlso 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 directorythrough underscore underscore D-I-R namewhich will give us the project directory, and it will havethe 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.

Resume Transcript Auto-Scroll

Author

Released

6/2/2015

If you've worked with JavaScript, you can quickly get up and running with Node.js, a lightweight and efficient platform for building network apps. Alexander Zanfir helps you write your first pieces of code and understand the frameworks available for the platform, including options such as Express, Sails, and Koa. He'll also help you create promises and generators, two unique aspects of Node.js. All this information is bundled into a small user authentication API Alexander creates along the way, which can be used as the stepping stone for the next full-scale app you build with Node.js.