Node.js / Express.js - create static folder

0 points
Created by:

In this article, we would like to show you how to create static folder in express.js.

Quick solution:



Practical example

In this example, we include express.static() middleware using app.use() method to create a static folder - public/ that contains two html files: index.html and about.html.


Below in the Project structure section you can see all the files within our project.

We also use path.join() method to specify the path to our static folder:

  • __dirname - current script directory path,
  • 'public' - name of the folder that we want to make static.

Practical example

const express = require('express');
const path = require('path');

const app = express();

// create a static folder
app.use(express.static(path.join(__dirname, 'public')));


Run the app and go to:

  • http://localhost:5000/ - to see the index.html file content
  • http://localhost:5000/about.html - to see the about.html file content


Node.js / Express.js - static folder - example result
Node.js / Express.js - static folder - example result
Node.js / Express.js - static folder - example result
Node.js / Express.js - static folder - example result

Project structure

 └─ project/
        ├─ node_modules/
        └─ public/
			  ├─ about.html
			  └─ index.html
        ├─ index.js
        ├─ package.json
        └─ package-lock.json

index.html file

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
    <h1>index.html file content</h1>

about.html file

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
    <h1>about.html file content</h1>

Alternative titles

  1. Node.js / Express.js - set static folder
  2. Node.js / Express.js - create static directory
  3. Node.js / Express.js - set static directory
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂