Sometimes, we want to serve an image using Node.js.
In this article, we’ll look at how to serve an image using Node.js.
How to serve an image using Node.js?
To serve an image using Node.js, we can use the middleware returned by express.static
.
For instance, we write
const path = require('path');
const express = require('express');
const app = express();
const dir = path.join(__dirname, 'public');
app.use(express.static(dir));
app.listen(3000, () => {
console.log('Listening on http://localhost:3000/');
});
to call app.use
with the middleware returned by express.static
called with the dir
of the image files.
This will expose the dir
folder to the public.
Conclusion
To serve an image using Node.js, we can use the middleware returned by express.static
.