Languages
[Edit]
EN

Node.js / Express.js - create static folder

0 points
Created by:
Wiktor-Sribiew
320

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_the_folder'));

 

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.

Note:

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 directory,
  • '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')));

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>
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