0
0
Node.jsframework~5 mins

Serving static files in Node.js

Choose your learning style9 modes available
Introduction

Serving static files lets your web server send images, styles, and scripts to users. It helps show pictures and design on websites.

You want to show images like logos or photos on your website.
You need to send CSS files to style your web pages.
You want to provide JavaScript files for interactive features.
You have downloadable files like PDFs or documents for users.
You want to serve favicon icons for browser tabs.
Syntax
Node.js
import express from 'express';
const app = express();

app.use(express.static('public'));

app.listen(3000);

The express.static middleware serves files from the folder you specify.

Files inside the folder are accessible by their path in the URL.

Examples
Serve all files inside the public folder at the root URL.
Node.js
app.use(express.static('public'))
Serve files from assets folder but under the URL path /static.
Node.js
app.use('/static', express.static('assets'))
Serve files but ignore hidden files starting with a dot.
Node.js
app.use(express.static('public', { dotfiles: 'ignore' }))
Sample Program

This program starts a server on port 3000. It sends any file inside the public folder when requested by the browser.

For example, if public/image.png exists, visiting http://localhost:3000/image.png will show that image.

Node.js
import express from 'express';

const app = express();

// Serve files from 'public' folder
app.use(express.static('public'));

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Make sure the folder you serve exists and has the files you want to share.

Static files are sent as-is, so update them carefully to avoid broken pages.

Use meaningful folder names like public or assets to keep your project organized.

Summary

Serving static files lets your server send images, CSS, and scripts to users.

Use express.static middleware to serve files from a folder.

Files inside the folder are accessible by their path in the browser URL.