How to fetch images from Node.js server ?

21 Nov, 2021
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:
Directory Tree:
server.js
package.json
package-lock.json
nodemoules
  | -- *
images
  | -- geeksforgeeks.png
public
  | -- index.html
Method 1: 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.
Filename: server.js
Javascript
// Requiring moduleconst express = require('express'); // Creating express objectconst app = express(); // Defining port numberconst PORT = 3000;                  // Function to serve all static files// inside public directory.app.use(express.static('public')); app.use('/images', express.static('images')); // Server setupapp.listen(PORT, () => {  console.log(`Running server on PORT ${PORT}...`);})
Steps to run the program:
1. Install express using the following command:
npm install express
2. Run the server.js file using the following command:
node server.js
 
3. 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
Method 2: Without using 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.
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.
Filename: server.js
Javascript
// Requiring modulesconst http = require("http");const fs = require("fs");const path = require("path");const url = require("url"); // Creating server to accept requesthttp.createServer((req, res) => {     // Parsing the URL    var request = url.parse(req.url, true);     // Extracting the path of file    var action = request.pathname;     // Path Refinements    var 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        var ext = path.extname(action);         // Setting default Content-Type        var 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:
1. Install express using the following command:
npm install express
2. Run the server.js file using the following command:
node server.js
3. 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
mridulmanochagfg
simmytarika5
surinderdawra388
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.