Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Serve Static Files with Express

    Mark ShustMark Shust

    In this lesson we will find out how to serve static assets (images, css, stylesheets, etc.) with Express. We will go over writing initial boilerplate for a simple Express app, and using Express's built-in middleware to serve these assets through a web server on Node.js.

    expressExpress
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Let's set up an Express app that serves up a simple request of an image of our cat friend. We'll first require the path module to do path lookups, and then require Express, our web server. Then we'll create an instance of Express.

    Let's define a route at the root of our address to serve up requests. We will call this on method on the response object with some simple HTML that sends back a header with an image of our cat friend.

    To serve up images, we'll need to use the built-in middleware for serving up static assets in Express. First, we call app.use, followed by the path to reply the middleware on, in this case, /images. Then we will call the Express static middleware with the path location where our static assets will be stored.

    By defining the absolute path with __dirname, we can run Express from any directory, and not worry about being in the relative path. We'll store our images in a folder at public/images. Finally, we will listen for requests on port 8080.

    Let's make our public/images directory, then copy our herman.jpg image to it. Now we'll install Express with yarn add express.

    Then we will start our web server with Nodeindex.js. Let's check our web browser to see our friend, Herman, being properly served up with Express.

    Discuss

    Discuss