Sometimes, we want to create a basic static file server in Node.js.
In this article, we’ll look at how to create a basic static file server in Node.js.
How to create a basic static file server in Node.js?
To create a basic static file server in Node.js, we can use Express.
To install it, we run
npm i express
Then we create a static file server with it by writing
const express = require('express')
const app = express()
const port = process.env.PORT || 4000;
app.use(express.static(__dirname + '/public'));
app.listen(port);
We call express.static with the folder with the static files we want to serve.
And we call app.use to use the middleware returned by express.static.
Then we call app.listen with port to start the server and listen at for traffic at the given port.
Conclusion
To create a basic static file server in Node.js, we can use Express.