Languages
[Edit]
EN

Express.js - create static folder

0 points
Created by:
Wiktor-Sribiew
800

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

Quick solution:

app.use(express.static('path/to/folder'));

 

Practical example

In this example, we use:

  • express.static() middleware included using app.use() method - that creates public/ static folder containing two HTML files: index.html and about.html.
  • 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.
const express = require('express');
const path = require('path');

const app = express();

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

app.listen(5000);

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

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
Node.js / Express.js - static folder - example result

Project structure

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

index.html file

// ONLINE-RUNNER:browser;

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

about.html file

// ONLINE-RUNNER:browser;

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

Alternative titles

  1. Express.js - set static folder
  2. Express.js - create static directory
  3. 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.

❤️💻 🙂

Join