ExpressJS — serving static files and html themes from local machine @ The Hacking School-6th-Week

Image for post
Image for post

6th week moving at the super-fast pace at The Hacking School and today had an awesome session with our lead instructor Prashant implementing the technique to serve static files and directories from Express server.

Image for post
Image for post
Image for post
Image for post

Showing list of Files and Directories in the local machine

Here’s my code using the npm module serve-index

In the above, I am using the npm packages serverIndex which returns a middlware that serves an index of the directory in the given path. In the code above, I am completely configuring the server with serverIndex’s methods without using Express. And the path is based off the req.url value, so a req.url of /some/dir with a path of public will look at public/some/dir.

However, if I am using Express, I can set the URL “base” with app.use. Below is the implementation using Express

Serving static html themes (full static web-site) from local machine

Here I am going to serve a static theme that I downloaded from https://templated.co/hielo so as soon as I start my express sever the entry root will launch the site.

Here’s the code

And that’s it. Now as soon as I fire up my server, a full blown beautiful website is up and running in my Express Server.

The entry point to my app is server.js and after I run node server.js the express server will start and in my code the app.use middleware will chain itself with another middleware express.static to sever the files in the directory public/templated-hielo

Express middlewares processes the incoming requests before handling them down to the routes. Each middleware layer is essentially adding a function that specifically handles something to your flow through the middleware.

I am using node’s path module to join all given path segments together using the platform specific separator as a delimiter, then normalizes the resulting path. Normalizing in that sense that, Windows does paths with backslashes where Unix does paths with forward slashes. path.join() will normalize these to use the correct slash. path.join will also take care of unneccessary delimiters, that may occur if the given paths come from unknown sources (eg. user input, 3rd party APIs etc.). So path.join(‘a/’,’b’) path.join(‘a/’,’/b’), path.join(‘a’,’b’) and path.join(‘a’,’/b’) will all give a/b.

And here’s the full source code of the project in my github.

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Written by

MachineLearning | DataScience | DeepLearning. Previously Frontend Engineer. Ex International Banking Analyst. https://www.linkedin.com/in/rohan-paul-b27285129/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store