How to Fetch Images from Node Server ?
Last Updated :
26 Jun, 2025
The images, CSS files, JavaScript files, and other files that the client downloads from the server are known as static files. These static files can be fetched with the use of the express framework and without the use of it. The methods that can be used to serve static files are discussed below. The image to be accessed (geeksforgeeks.png) is placed inside the images folder, as shown in the directory tree below:
Project Structure:
We will discuss the following approaches to fetch images from Node server:
Using the Express framework
Using the Express framework its built-in middleware function express.static() can be used to serve static files.
Syntax:
express.static(root, [options])
Parameters:
This method accepts two parameters as mentioned above and described below:
- root: It specifies the directory from which the static files are to be served. Basically, all the static files reside in the public directory.
- options: It is used to specify other options which you can read more about here.
Example: The following code is an example of how to get an image or other static files from the node server.
Node
// Requiring module
const express = require('express');
// Creating express object
const app = express();
// Defining port number
const PORT = 3000;
// Function to serve all static files
// inside public directory.
app.use(express.static('public'));
app.use('/images', express.static('images'));
// Server setup
app.listen(PORT, () => {
console.log(`Running server on PORT ${PORT}...`);
})
Steps to run the program:
node server.js
Output: Open any browser and to go http://localhost:3000/images/geeksforgeeks.png and you will see the following output:
The output of the above commandWithout the Express Framework
To serve static files using the fundamentals of Node.js, we can follow these steps:
- Parse the incoming HTTP request, to know the requested path.
- Check if the path exists to respond to status as success or not found (optional).
- Get the extension of the file to set content-type.
- Serve the content-type in the header and serve the requested file in response.
Example: The following code is an example of how to get an image or other static files from the node server.
Node
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");
http.createServer((req, res) => {
const request = url.parse(req.url, true);
const action = request.pathname;
const filePath = path.join(__dirname, action).split("%20").join(" ");
fs.exists(filePath, function (exists) {
if (!exists) {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("404 Not Found");
return;
}
const ext = path.extname(action);
let contentType = "text/plain"; // Default content type
// Checking if the extension of the image is '.png'
if (ext === ".png") {
contentType = "image/png";
}
// Setting the headers
res.writeHead(200, {
"Content-Type": contentType
});
// Reading the file
fs.readFile(filePath, function (err, content) {
if (err) {
res.writeHead(500);
res.end("Server Error");
return;
}
// Serving the image
res.end(content);
});
});
})
// Listening to the PORT: 3000
.listen(3000, "127.0.0.1");
Steps to run the program:
node server.js
Output: Open any browser and to go http://localhost:3000/images/geeksforgeeks.png and you will see the following output:
The output of the above command
Similar Reads
How to Load NextJS Images from an External URL ? In Next.js, loading external URL images is important because it allows developers to incorporate dynamic content and enrich user experiences by displaying images from various sources seamlessly within their applications.In this article, we will explore two different approaches to loading NextJS Imag
2 min read
How to Retrieve Data from MongoDB Using NodeJS? MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How to Run Node Server? A Node server runs JavaScript outside the browser to handle web requests. It listens for incoming requests, processes them, and sends responses. Unlike traditional servers, it handles multiple requests at once without waiting for each to finish.Some of the key features of the Node Server are:Non-Blo
3 min read
How to Cache Images in React Native? Caching images in React Native enhances app performance by reducing network load and improving image load times. By storing frequently accessed images locally, the app can quickly display them without needing to re-download, resulting in a smoother and faster user experience. Caching images in React
2 min read
How To Create a Simple HTTP Server in Node? NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
3 min read