There are several ways to serve static files in Express.
built-in function: static
We can use express.static built-in middleware function in Express to let users access those files.
The Function is like this:
The root argument specifies the directory from the server.
For example, if you want to let your homepage folder be one of the routes, you can use app.use(express.static(‘homepage’)); Thus, you can access your homepage file using the URL below: http://localhost:3000/homepage.html.
Express will call the express.static middleware functions in order base on the file. For instance, if there are two same files under the homepage and customer folder, check the code below.
Express will show the file under the homepage folder first.
We can also add a virtual path prefix for the file using app.use() function.
The URL will be http://localhost:3000/static/homepage.html
File directory issue: wrong directory
We introduce the expresss.static function to serve the static file. However, the default directory of this function is relative to the directory from where you execute your node command. So it may cause another issue if your application runs in a different location. To solve this issue, we can use path.join to assign the absolute path of the directory. We can use the code like below:
App.use(‘/static’, express.static(path.join(_dirname, ‘homepage’)))