How to use the static function from express

Find comprehensive JavaScript express.static code examples handpicked from public code repositorys.

express.static is a middleware function in Express.js that serves static files such as HTML, images, and CSS.

2464
2465
2466
2467
2468
2469
2470
2471
2472
2473

const { app } = this

this.app.use(
  "/monaco-editor",
  express.static(path.join(nodeModulesFolder, "monaco-editor"))
)

const searchCache = {}
app.get("/search.html", (req, res) => {
fork icon73
star icon641
watch icon6

56
57
58
59
60
61
62
63
64
65
66
  process.env.VOLUMIO_3_UI = 'false';
} else {
  process.env.VOLUMIO_3_UI = 'true';
}


var staticMiddlewareUI2 = express.static(path.join(__dirname, 'www'));
var staticMiddlewareUI3 = express.static(path.join(__dirname, 'www3'));
var staticMiddlewareManifestUI = express.static(path.join(__dirname, 'www4'));
var staticMiddlewareWizard = express.static(path.join(__dirname, 'wizard'));

fork icon28
star icon21
watch icon4

+ 6 other calls in file

How does express.static work?

express.static is a built-in middleware function in Express.js that is used to serve static files from a specified directory such as HTML, CSS, images, and JavaScript files in response to HTTP requests. When a request is received by the server, the express.static middleware checks the specified directory and returns the corresponding file if it exists. It automatically sets the Content-Type header based on the file type and sends the file to the client.

197
198
199
200
201
202
203
204
205
206
const app = express()
  .use(require('compression')())
  .set('view engine', 'ejs')
  // Statically serve the archive
  .use('/archive', require('serve-index')(config.newsstand))
  .use('/archive', express.static(config.newsstand))
  // Main pages
  .get('/', (req, res) => res.render('index', {db: db}))
  .get('/latest/:deviceId?', (req, res) => {
    const reqInfo = `GET ${req.originalUrl} from ${req.ip} (${req.headers['user-agent']}): Prev=[${req.query.prev}]; DeviceId=[${req.params.deviceId}]`
fork icon0
star icon28
watch icon1

70
71
72
73
74
75
76
77
78
79
  rolling: true,
  store: new MongoStore({
    mongooseConnection: mongoose.connection
  })
}),
express.static(__dirname+'/static'),
passport.initialize(),
passport.session(),
flash(),
function(req, res, next) {
fork icon0
star icon2
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
const express = require("express");
const app = express();

// Serve static files from the "public" directory
app.use(express.static("public"));

// Start the server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

In this example, express.static is used as middleware to serve static files from the "public" directory when a GET request is made to the server. The app.use function is used to mount the middleware. The express.static function takes a string argument that specifies the directory from which to serve the files.

114
115
116
117
118
119
120
121
122
123
124
app.use('/assets', express.static(path.join(govukFrontendRoot, 'govuk', 'assets')));
app.use(
	'/assets/jquery.js',
	express.static(path.join(jQueryFrontendRoot, 'dist', 'jquery.min.js'))
);
app.use('/assets/govuk/all.js', express.static(path.join(govukFrontendRoot, 'govuk', 'all.js')));


function isProjectClosed(req, res, next) {
	const { isPeriodOpen } = req.session;

fork icon1
star icon1
watch icon5

+ 2 other calls in file

1007
1008
1009
1010
1011
1012
1013
1014
1015
1016

app.get("/", (req,res)=>{res.sendFile(path.join(__dirname,"website/index.html"))})
app.get("/index.html", (req,res)=>{res.sendFile(path.join(__dirname,"website/index.html"))})
app.use("/static/", express.static(path.join(__dirname, "/website_res/")))

app.use("/dvr/", express.static(config.dvr_path.replace(/\(pathname\)/g, __dirname), {index: false, setHeaders: (res, path) => {
    if (path.endsWith(".m3u8")) {
        res.header('Content-Type', 'application/x-mpegurl')
    }
}}))
fork icon0
star icon1
watch icon1

+ 7 other calls in file

31
32
33
34
35
36
37
38
39
40
41
42
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const port = process.env.PORT || 8081;
const qrcode = require("qrcode");


app.use("/assets", express.static(__dirname + "/client/assets"));


app.get("/scan", (req, res) => {
  res.sendFile("./client/server.html", {
    root: __dirname,
fork icon1
star icon0
watch icon1

+ 3 other calls in file

11
12
13
14
15
16
17
18
19
20
// 프로세서의 주소 포트번호
const port = 8080;
const multer = require("multer");
// 브라우져의 cors이슈를 막기 위해 설정
app.use(cors());
app.use("/upload", express.static("upload"));
// json형식 데이터를 처리하도록 설정
app.use(express.json());
// upload폴더 클라이언트에서 접근 가능하도록 설정

fork icon0
star icon0
watch icon1

+ 2 other calls in file

0
1
2
3
4
5
6
7
8
9
10
const express = require('express');
const app = express();
const Puerto = 8080;


app.use("/resources", express.static("public"));
app.use("/resources", express.static(__dirname + "/public"));
//4- Estableciendo el motor de plantillas
app.set('view engine','ejs');
//Para poder capturar los datos del formulario (sin urlencoded nos devuelve "undefined")
app.use(express.urlencoded({extended:false}));
fork icon0
star icon0
watch icon1

19
20
21
22
23
24
25
26
27
28
29
30
31


//parser
app.use(bodyParser.json());


//Image static folder
app.use('/storage', express.static('./storage'))


//fix cors
app.use(cors());

fork icon0
star icon0
watch icon1

46
47
48
49
50
51
52
53
54
55
const { ifError } = require("assert");
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: true }));   //Parse body req as json.
app.use('/', express.static(__dirname + '/'));
app.use('/', express.static(__dirname + '/upload/Allentown/')); // Store static files.
// Store static files.
app.use('/api/v1', require('./client_route_magellan.js'));
app.use('/api/nj', require('./nj'));
app.use('/api/se', require('./se'));
fork icon0
star icon0
watch icon1

60
61
62
63
64
65
66
67
68
69
70
71
    origin: ['http://localhost:3000'],
    credentials: true,
  })
)


app.use('/public/upload', express.static('./public/upload'))


app.get('/', (req, res, next) => {
  res.send('Hello Express')
  next()
fork icon0
star icon0
watch icon1

58
59
60
61
62
63
64
65
66
67
    })    
 
}
app.use(authentication)
app.use(express.json());
app.use('/app', express.static(path.join(__dirname,  'Instalador')));
app.use(fileUpload({
    createParentPath: true,
    limits: { 
        fileSize: 20 * 1024 * 1024 //20MB max
fork icon0
star icon0
watch icon1

22
23
24
25
26
27
28
29
30
31
32
33
	secret: 'secret',
	resave: true,
	saveUninitialized: true
}));
// app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static("public", {redirect: false}));


app.set("view engine", "ejs");


const PORT = 80;
fork icon0
star icon0
watch icon1

445
446
447
448
449
450
451
452
453
454

// Enable All CORS Requests
app.use(cors());

// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));

// Parse Server plays nicely with the rest of your web routes
app.get('/', function(_req, res) {
  res.status(200).send('I dream of being a website. Please star the parse-hipaa repo on GitHub!');
fork icon0
star icon0
watch icon1

2
3
4
5
6
7
8
9
10
11
12
13
14
15


const methodOverride = require(`method-override`)
const db = require(`../db`)


urlEncoded = express.urlencoded({ extended: true})
static = express.static(`public`)




const method_override = methodOverride((req, res) => {
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

18
19
20
21
22
23
24
25
26
27
28
29
30


// テンプレートエンジンの設定
app.set("view engine", "ejs");


// htmlやcssファイルが保存されている publicフォルダ を指定
app.use("/static", express.static(path.join(__dirname, "public")));


// DBに接続
var pool = new pg.Pool({
  database: "postgres",
fork icon0
star icon0
watch icon1

+ 2 other calls in file

141
142
143
144
145
146
147
148
149
150
if (process.env.NODE_ENV === 'development') {
  maxAge = 1;
  console.log('Development environment detected, setting static file cache age to 1 second');
}

var staticFiles = express.static(resolvePath(env.static_files), {
  maxAge
});

// serve the static content
fork icon0
star icon0
watch icon1

+ 8 other calls in file

47
48
49
50
51
52
53
54
55
56
57
58
59
60


// built-in middleware for json
app.use(express.json());


// serve static files
app.use('/', express.static(path.join(__dirname, '/public')));


app.use('/subdir', express.static(path.join(__dirname, '/public')));


// routes
fork icon0
star icon0
watch icon1

136
137
138
139
140
141
142
143
144
145
146
147


// Static Files
app.use(express.static('public'));
// Specific folder example
// app.use('/css', express.static(dirname + 'public/css'))
app.use('/js', express.static(__dirname + '/public/js'));
// app.use('/img', express.static(dirname + 'public/images'))


// Set View's
app.set('views', './views');
fork icon0
star icon0
watch icon1

+ 2 other calls in file