Sometimes developers want to serve some static asset from node_modules. Usually, we don’t want to expose any of your internal paths to the outside world. If your files are in the node_modules directory then you can make a static route in your server that fetches its files from whatever directory you specify.
The express.static() function is used to serve the static files from a directory, use the express.static() built-in middleware function in Express.
Parameters: This function accepts the following two parameters:
- root: The root parameter specifies the directory from where you want to serve the static file.
- options: It is an optional parameter that contains property like etag, dotfiles, etc.
For example, if you want to serve static assets from folder name public, then use the following code.
Now, your app can serve static resources on all URLs.
Example: To serve bootstrap CSS files from the node_modules directory.
Step 1: First, create a NodeJS application and install the required modules like Express.js and bootstrap.
mkdir Project cd Project npm init -y npm i express bootstrap
Step 2: Create an index.js file which is our basic server with the following code.
Step 3: Create an index.html file in your root directory with the following code.
Explanation: The stylesheet’s URL is /bootstrap/bootstrap.min.css where /bootstrap is the virtual prefix. So when the server receives a request from this URL, the server lookup the specified file on your specified static path node_modules/bootstrap/dist/css and sends it to the client.
Step 4: Run the server with the following command:
Output: You will see the following output on the terminal screen.
Server listening on Port 3000
Now open any browser and go to http://localhost:3000/, you will see the following output.