Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Load NextJS Images from an External URL ?
Next article icon

How to Fetch Images from Node Server ?

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Screenshot-2024-06-07-125653

We will discuss the following approaches to fetch images from Node server:

Table of Content

  • Using the Express framework
  • Without the Express Framework

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 command

Without 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
// Requiring modules const http = require("http"); const fs = require("fs"); const path = require("path"); const url = require("url");  // Creating server to accept request http.createServer((req, res) => {      // Parsing the URL     const request = url.parse(req.url, true);      // Extracting the path of file     const action = request.pathname;      // Path Refinements     const filePath = path.join(__dirname,         action).split("%20").join(" ");      // Checking if the path exists     fs.exists(filePath, function (exists) {          if (!exists) {             res.writeHead(404, {                 "Content-Type": "text/plain"             });             res.end("404 Not Found");             return;         }          // Extracting file extension         const ext = path.extname(action);          // Setting default Content-Type         const contentType = "text/plain";          // Checking if the extension of         // 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) {                 // 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



Next Article
How to Load NextJS Images from an External URL ?
author
thinkswell
Improve
Article Tags :
  • Node.js
  • Technical Scripter
  • Web Technologies
  • NodeJS-Questions
  • Technical Scripter 2020

Similar Reads

  • How to Connect to Telnet Server from Node.js ?
    Connecting to a Telnet server from Node.js involves creating a client that can communicate using the Telnet protocol. Telnet is a protocol used to establish a connection to a remote host to execute commands and transfer data. In Node.js, you can use various packages to facilitate the connection to a
    4 min read
  • 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 Ima
    3 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-B
    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 Build a Node.js Proxy Server ?
    A proxy server acts as an intermediary between a client and other servers. It can be used for various purposes, including load balancing, security, and caching. In the context of web development, a proxy server forwards requests from clients to other servers, fetches responses, and sends them back t
    4 min read
  • How To Create A Custom Image Loader In NextJS?
    Creating a custom image loader in Next.js allows you to control how images are loaded and optimized. This is useful for integrating with different image services or handling specific image processing needs. Here’s how to create and use a custom image loader: This article will walk you through the st
    4 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
  • How to make HTTP requests in Node ?
    In the world of REST API, making HTTP requests is the core functionality of modern technology. Many developers learn it when they land in a new environment. Various open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used to make network requests from NodeJS. There are many
    4 min read
  • How to Access the File System in Node.js ?
    In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences