serving static files in nodejs Node.js
In an Express.js application, you can serve static files such as images, CSS files, and JavaScript files by using the built-in express.static
middleware.
Here's an example of how to serve static files in an Express.js application:
Create a new directory called
public
in your project directory, and add some static files to it (e.g.,public/index.html
,public/styles.css
, andpublic/script.js
).In your Express.js application, add the following code to serve the static files:
const express = require('express') const app = express() // serve static files from the "public" directory app.use(express.static('public')) app.listen(3000, () => { console.log('Server started on port 3000') })
In this code, we use the express.static
middleware to serve static files from the public
directory. Any files in the public
directory can now be accessed by their URL relative to the root of the server (e.g., http://localhost:3000/index.html
, http://localhost:3000/styles.css
, and http://localhost:3000/script.js
).
- Start the server using the following command:
node index.js
You should see a message in the console indicating that the server has started.
- Open your web browser and navigate to
http://localhost:3000/index.html
. You should see theindex.html
file displayed in your browser, along with any CSS and JavaScript files it references.