194

I have a logo that is residing at the public/images/logo.gif. Here is my nodejs code.

http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain' });
  res.end('Hello World \n');
}).listen(8080, '127.0.0.1');

It works but when I request for localhost:8080/logo.gif then I obviously don't get the logo.

What changes I need to do to serve an image.

Ahmed Nour Eldeen
  • 351
  • 1
  • 4
  • 13
Nick Vanderbilt
  • 36,724
  • 29
  • 83
  • 106

13 Answers13

328

2016 Update

Examples with Express and without Express that actually work

This question is over 5 years old but every answer has some problems.

TL;DR

Scroll down for examples to serve an image with:

  1. express.static
  2. express
  3. connect
  4. http
  5. net

All of the examples are also on GitHub: https://github.com/rsp/node-static-http-servers

Test results are available on Travis: https://travis-ci.org/rsp/node-static-http-servers

Introduction

After over 5 years since this question was asked there is only one correct answer by generalhenry but even though that answer has no problems with the code, it seems to have some problems with reception. It was commented that it "doesn't explain much other than how to rely on someone else to get the job done" and the fact how many people have voted this comment up clearly shows that a lot of things need clarification.

First of all, a good answer to "How to serve images using Node.js" is not implementing a static file server from scratch and doing it badly. A good answer is using a module like Express that does the job correctly.

Answering comments that say that using Express "doesn't explain much other than how to rely on someone else to get the job done" it should be noted, that using the http module already relies on someone else to get the job done. If someone doesn't want to rely on anyone to get the job done then at least raw TCP sockets should be used instead - which I do in one of my examples below.

A more serious problem is that all of the answers here that use the http module are broken. They introduce race conditions, insecure path resolution that will lead to path traversal vulnerability, blocking I/O that will completely fail to serve any concurrent requests at all and other subtle problems - they are completely broken as examples of what the question asks about, and yet they already use the abstraction that is provided by the http module instead of using TCP sockets so they don't even do everything from scratch as they claim.

If the question was "How to implement static file server from scratch, as a learning exercise" then by all means answers how to do that should be posted - but even then we should expect them to at least be correct. Also, it is not unreasonable to assume that someone who wants to serve an image might want to serve more images in the future so one could argue that writing a specific custom static file server that can serve only one single file with hard-coded path is somewhat shortsighted. It seems hard to imagine that anyone who searches for an answer on how to serve an image would be content with a solution that serves just a single image instead of a general solution to serve any image.

In short, the question is how to serve an image and an answer to that is to use an appropriate module to do that in a secure, performant and reliable way that is readable, maintainable and future-proof while using the best practice of professional Node development. But I agree that a great addition to such an answer would be showing a way to implement the same functionality manually but sadly every attempt to do that has failed so far. And that is why I wrote some new examples.

After this short introduction, here are my five examples doing the job on 5 different levels of abstraction.

Minimum functionality

Every example serves files from the public directory and supports the minimum functionality of:

  • MIME types for most common files
  • serves HTML, JS, CSS, plain text and images
  • serves index.html as a default directory index
  • responds with error codes for missing files
  • no path traversal vulnerabilities
  • no race conditions while reading files

I tested every version on Node versions 4, 5, 6 and 7.

express.static

This version uses the express.static built-in middleware of the express module.

This example has the most functionality and the least amount of code.

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

express

This version uses the express module but without the express.static middleware. Serving static files is implemented as a single route handler using streams.

This example has simple path traversal countermeasures and supports a limited set of most common MIME types.

var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.get('*', function (req, res) {
    var file = path.join(dir, req.path.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        return res.status(403).end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.set('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.set('Content-Type', 'text/plain');
        res.status(404).end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

connect

This version uses the connect module which is a one level of abstraction lower than express.

This example has similar functionality to the express version but using slightly lower-lever APIs.

var path = require('path');
var connect = require('connect');
var app = connect();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.use(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

http

This version uses the http module which is the lowest-level API for HTTP in Node.

This example has similar functionality to the connect version but using even more lower-level APIs.

var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

net

This version uses the net module which is the lowest-level API for TCP sockets in Node.

This example has some of the functionality of the http version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.

var path = require('path');
var net = require('net');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = net.createServer(function (con) {
    var input = '';
    con.on('data', function (data) {
        input += data;
        if (input.match(/\n\r?\n\r?/)) {
            var line = input.split(/\n/)[0].split(' ');
            var method = line[0], url = line[1], pro = line[2];
            var reqpath = url.toString().split('?')[0];
            if (method !== 'GET') {
                var body = 'Method not implemented';
                con.write('HTTP/1.1 501 Not Implemented\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
            if (file.indexOf(dir + path.sep) !== 0) {
                var body = 'Forbidden';
                con.write('HTTP/1.1 403 Forbidden\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var type = mime[path.extname(file).slice(1)] || 'text/plain';
            var s = fs.readFile(file, function (err, data) {
                if (err) {
                    var body = 'Not Found';
                    con.write('HTTP/1.1 404 Not Found\n');
                    con.write('Content-Type: text/plain\n');
                    con.write('Content-Length: '+body.length+'\n\n');
                    con.write(body);
                    con.destroy();
                } else {
                    con.write('HTTP/1.1 200 OK\n');
                    con.write('Content-Type: '+type+'\n');
                    con.write('Content-Length: '+data.byteLength+'\n\n');
                    con.write(data);
                    con.destroy();
                }
            });
        }
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

Download examples

I posted all of the examples on GitHub with more explanation.

Examples with express.static, express, connect, http and net:

Other project using only express.static:

Tests

Test results are available on Travis:

Everything is tested on Node versions 4, 5, 6, and 7.

See also

Other related answers:

Samuel RIGAUD
  • 623
  • 7
  • 21
rsp
  • 107,747
  • 29
  • 201
  • 177
  • 3
    There should be a way to way to revamp vintage questions such as this! I just wasted an hour or so trying to get the 110 vote response to work. Finally I scrolled down just to check. Your answer could (should) be a textbook on the topic. – Thailandian Feb 12 '17 at 23:08
  • 4
    I do not know why anyone would use Express. I did too at the start probably because everyone else did. Then I realized that using Node's http module is the right approach. That is what it is provided for. You get a lot of flexibility. You understand HTTP protocol and you can debug easily. Express provides a lot of jargon and a thin layer over the http module which is easy to implement with raw coding with the http module. **I strongly recommend any user of Express or any other such module to move away from them and use http module directly.** – Sunny Aug 14 '18 at 05:55
  • Great answer. But I have a question. If the image is very big, if it's possible to serve the image with multipart? Any example? Thanks. – Bagusflyer Sep 18 '18 at 06:25
  • 1
    a note i would like to mention for newbies like me: when we declare a folder as static using `express.static` we can fetch the image by calling the url `http://ip:port/path_after_the_static_folder` ,we do not need to mention the static folder itself to serve the image. Though we can add that by using `app.use('/static', express.static(imagePath))` for convenience as par documentation in: https://expressjs.com/en/starter/static-files.html – Rakibul Haq Feb 10 '19 at 09:05
  • also if there are nested folders, they are needed to be declared as static using `espress.static` too for those paths to be served for images or other files. – Rakibul Haq Feb 10 '19 at 09:10
  • 1
    Nice coverage in this answer, going progressively lower in abstractions is a good approach. It's a good resource for me; if you're curious to hear why people are reading this kind of stuff, personally I'm starting with node.js but I might eventually implement some html status pages on very low spec, esoteric hardware that can't even run javascript. Both the client and server will be weak computers on a LAN (no internet access). – jrh May 26 '19 at 19:40
  • The 1st answer (`express.static`) still works in 2019 with `node` version `10.8.0` and `express@4.17.1` – Nathan majicvr.com Sep 19 '19 at 14:44
  • 1
    The reason people are asking for an answer that doesn't involve express is that they want to understand how node works, at the level of Node without a framework. Those same people would probably also be happy to learn how TCP sockets work. Those who enjoy to write code, enjoy understanding, and learning a framework generally gives a person the information needed to get the job done, but not the information needed to understand how that job is getting done. It is more than just understanding 'HOW', it is the understanding 'WHY'. – JΛYDΞV Mar 21 '20 at 23:00
  • I use this answer to practice using some of the above libraries in my studies. – StayCool Apr 05 '23 at 04:41
177

I agree with the other posters that eventually, you should use a framework, such as Express.. but first you should also understand how to do something fundamental like this without a library, to really understand what the library abstracts away for you.. The steps are

  1. Parse the incoming HTTP request, to see which path the user is asking for
  2. Add a pathway in conditional statement for the server to respond to
  3. If the image is requested, read the image file from the disk.
  4. Serve the image content-type in a header
  5. Serve the image contents in the body

The code would look something like this (not tested)

fs = require('fs');
http = require('http');
url = require('url');


http.createServer(function(req, res){
  var request = url.parse(req.url, true);
  var action = request.pathname;

  if (action == '/logo.gif') {
     var img = fs.readFileSync('./logo.gif');
     res.writeHead(200, {'Content-Type': 'image/gif' });
     res.end(img, 'binary');
  } else { 
     res.writeHead(200, {'Content-Type': 'text/plain' });
     res.end('Hello World \n');
  }
}).listen(8080, '127.0.0.1');
CraigTeegarden
  • 8,173
  • 8
  • 38
  • 43
noli
  • 15,927
  • 8
  • 46
  • 62
  • 33
    You shouldn't use readFileSync in the middle of a response. Either a sync load should be used on the first tic or the async method should be used. codr.cc/s/5d0b73d6/js – generalhenry Apr 29 '11 at 03:01
  • 1
    I'm on board with you on the sync version, for the async version though, I thought the danger of using non-blocking operations for files, was that it could send the response before the entire file was read, and end up leaving you with a partial file being served to the user? Do you need to use chunked encoding if you use an async file read? – noli Apr 29 '11 at 03:08
  • 1
    fs.readFileSync doesn't callback until the whole file is loaded so there's no need for chunk handling. Chunk handling is mostly for network file transfer (since things can take longer than expected). – generalhenry Apr 29 '11 at 04:41
  • 10
    The line `res.end(img);` should be `res.end(img, 'binary');`. Good work! – Honza Pokorny Jul 01 '11 at 22:46
  • 1
    You should also know what the framework does, because sometimes it's just easier for simpler sites and although its more complex, bigger sites will be more customizable. The main advantage is if express doesn't help you in certain scenarios, you can just code native http server instead of looking through forums and documentation. –  Oct 20 '13 at 07:14
  • res.end() doesn't work `TypeError: 'undefined' is not a function (evaluating 'res.end()')` – holms Mar 30 '14 at 19:40
  • 4
    +1 for "but first you should also understand how to do something fundamental like this without a library, to really understand what the library abstracts away for you.." – Sunny Nov 11 '15 at 08:37
  • You should **never** use any blocking (Sync) function in any callback. Doing so results in serious problems. See [my answer](https://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767) for examples on how to implement static server with pure `http` (and even without it) with no blocking operations at all. – rsp Nov 30 '16 at 23:23
  • @holms If you want something that works then see the examples in [my answer](http://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767). All of them are tested with Travis on Node versions 4, 5, 6 and 7. – rsp Dec 01 '16 at 09:35
  • seems like a production approach would be to put something like FastCGI infront of NodeJS to serve all those static files, right? – Itay Moav -Malimovka Sep 03 '18 at 14:48
87

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
generalhenry
  • 17,227
  • 4
  • 48
  • 63
  • 26
    Safe, but doesn't explain much other than how to rely on someone else to get the job done. – Lee Goddard Sep 24 '14 at 19:45
  • I added a vanilla node (just core modules) version. – generalhenry Sep 24 '14 at 20:03
  • 1
    +I This is the only correct answer posted so far. I explain it in [my answer](http://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767) in more details. – rsp Nov 30 '16 at 22:56
29

var http = require('http');
var fs = require('fs');

http.createServer(function(req, res) {
  res.writeHead(200,{'content-type':'image/jpg'});
  fs.createReadStream('./image/demo.jpg').pipe(res);
}).listen(3000);
console.log('server running at 3000');
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
  • simple and to the point, way better than the express answers.. this deserves 1000 upvotes. Just a tip: maybe remove the code snippet and replace it with just javascript text – B''H Bi'ezras -- Boruch Hashem Nov 25 '19 at 04:01
  • would it be possible to pass a parameter so that './image/:jpg can serve any picture? – Prav Jan 29 '20 at 18:13
  • @Prav kind of I used query params, but then you need some kind of regex to check for it, like so ```const { url} = req; if (url.match(/^\/img.+/)) { const name = url.split("name=").pop(); }``` – 8koi Jan 03 '23 at 03:45
19

It is too late but helps someone, I'm using node version v7.9.0 and express version 4.15.0

if your directory structure is something like this:

your-project
   uploads
   package.json
   server.js

server.js code:

var express         = require('express');
var app             = express();
app.use(express.static(__dirname + '/uploads'));// you can access image 
 //using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.

//Or you can change the directory for hiding real directory name:

`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg


app.listen(7000);
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130
  • Was trying to access a static folder using "http://localhost:7000/uploads/abc.jpg". Thank you for your comment about removing the folder and just using "http://localhost:7000/abc.jpg" – user4889134 Feb 26 '21 at 12:59
14

Vanilla node version as requested:

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

http.createServer(function(req, res) {
  // parse url
  var request = url.parse(req.url, true);
  var action = request.pathname;
  // disallow non get requests
  if (req.method !== 'GET') {
    res.writeHead(405, {'Content-Type': 'text/plain' });
    res.end('405 Method Not Allowed');
    return;
  }
  // routes
  if (action === '/') {
    res.writeHead(200, {'Content-Type': 'text/plain' });
    res.end('Hello World \n');
    return;
  }
  // static (note not safe, use a module for anything serious)
  var filePath = path.join(__dirname, action).split('%20').join(' ');
  fs.exists(filePath, function (exists) {
    if (!exists) {
       // 404 missing files
       res.writeHead(404, {'Content-Type': 'text/plain' });
       res.end('404 Not Found');
       return;
    }
    // set the content type
    var ext = path.extname(action);
    var contentType = 'text/plain';
    if (ext === '.gif') {
       contentType = 'image/gif'
    }
    res.writeHead(200, {'Content-Type': contentType });
    // stream the file
    fs.createReadStream(filePath, 'utf-8').pipe(res);
  });
}).listen(8080, '127.0.0.1');
barryels
  • 143
  • 2
  • 5
generalhenry
  • 17,227
  • 4
  • 48
  • 63
  • 2
    You don't want to check for `fs.exists` (race condition), it'd be a better habit to catch an error when piping. – Brendan Sep 27 '14 at 02:00
  • Though checking exists in this case isn't the node way, everything else about this answer is 1 million times better than the accepted answer. – Ninjaxor May 27 '16 at 00:29
  • 1
    I agree with @BrendanAshworth. The race conditions are present in almost all of the answers here. I wrote more about it in [my answer](http://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767). But Kudos for writing it with streams. Almost all other answers use readFileSync which is blocking and should not be used in any event handlers. – rsp Dec 01 '16 at 09:33
  • 1
    var filePath = path.resolve('public', '.' + parts.pathname); response.writeHead(200, {'Content-Type': mime.lookup(parts.pathname)}); mime - package mime-type from npm – Rijen Jun 15 '19 at 04:38
13

I like using Restify for REST services. In my case, I had created a REST service to serve up images and then if an image source returned 404/403, I wanted to return an alternative image. Here's what I came up with combining some of the stuff here:

function processRequest(req, res, next, url) {
    var httpOptions = {
        hostname: host,
        path: url,
        port: port,
        method: 'GET'
    };

    var reqGet = http.request(httpOptions, function (response) {
        var statusCode = response.statusCode;

        // Many images come back as 404/403 so check explicitly
        if (statusCode === 404 || statusCode === 403) {
            // Send default image if error
            var file = 'img/user.png';
            fs.stat(file, function (err, stat) {
                var img = fs.readFileSync(file);
                res.contentType = 'image/png';
                res.contentLength = stat.size;
                res.end(img, 'binary');
            });

        } else {
            var idx = 0;
            var len = parseInt(response.header("Content-Length"));
            var body = new Buffer(len);

            response.setEncoding('binary');

            response.on('data', function (chunk) {
                body.write(chunk, idx, "binary");
                idx += chunk.length;
            });

            response.on('end', function () {
                res.contentType = 'image/jpg';
                res.send(body);
            });

        }
    });

    reqGet.on('error', function (e) {
        // Send default image if error
        var file = 'img/user.png';
        fs.stat(file, function (err, stat) {
            var img = fs.readFileSync(file);
            res.contentType = 'image/png';
            res.contentLength = stat.size;
            res.end(img, 'binary');
        });
    });

    reqGet.end();

    return next();
}
occasl
  • 5,303
  • 5
  • 56
  • 81
  • You should **never** use readFileSync inside of event handlers. This is a synchronous operation that blocks your entire process while it reads the file. I explained it in [my answer](http://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767) in more detail. – rsp Dec 01 '16 at 09:42
4

This may be a bit off-topic, since you are asking about static file serving via Node.js specifically (where fs.createReadStream('./image/demo.jpg').pipe(res) is actually a good idea), but in production you may want to have your Node app handle tasks, that cannot be tackled otherwise, and off-load static serving to e.g Nginx.

This means less coding inside your app, and better efficiency since reverse proxies are by design ideal for this.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
marko-36
  • 1,309
  • 3
  • 23
  • 38
3

This method works for me, it's not dynamic but straight to the point:

const fs      = require('fs');
const express = require('express');
const app     = express();

app.get( '/logo.gif', function( req, res ) {

  fs.readFile( 'logo.gif', function( err, data ) {

    if ( err ) {

      console.log( err );
      return;
    }

    res.write( data );
    return res.end();
  });

});

app.listen( 80 );
Nouman
  • 6,947
  • 7
  • 32
  • 60
3

Let me just add to the answers above, that optimizing images, and serving responsive images helps page loading times dramatically since >90% of web traffic are images. You might want to pre-process images using JS / Node modules such as imagemin and related plug-ins, ideally during the build process with Grunt or Gulp.

Optimizing images means processing finding an ideal image type, and selecting optimal compression to achieve a balance between image quality and file size.

Serving responsive images translates into creating several sizes and formats of each image automatically and using srcset in your HTML allows you to serve optimal image set (that is, the ideal format and dimensions, thus optimal file size) for every single browser).

Image processing automation during the build process means incorporating it up once, and presenting optimized images further on, requiring minimum extra time.

Some great read on responsive images, minification in general, imagemin node module and using srcset.

Ahmed Nour Eldeen
  • 351
  • 1
  • 4
  • 13
2

//This method involves directly integrating HTML Code in the res.write
//first time posting to stack ...pls be kind

const express = require('express');
const app = express();
const https = require('https');

app.get("/",function(res,res){
    res.write("<img src="+image url / src +">");
    res.send();
});

app.listen(3000, function(req, res) {
  console.log("the server is onnnn");
});
0
import http from "node:http";
import fs from "node:fs";

http.createServer((req, res)=>{
    if(req.url === "/" && req.method === "GET"){
        res.writeHead(200, {
            "Content-Type" : "image/jpg"
        })
        fs.readFile("someimage.jpg", (err, data)=>{
            if(err){
                throw err;
            }
             res.write(data);
             res.end();
        })
    }
}).listen(8080);
Siva Kumar
  • 1
  • 1
  • 1
  • 3
0

Does express support HTTP/3? Nope.

How about HTTP/2? Nope.

I guess future proof didn't work out.

The problem of depending on a module that isn't updated quickly when standards change. Be advised.

Walt Howard
  • 7,676
  • 1
  • 16
  • 11