Categories
JavaScript Answers

How to create a quick file server with Node.js to server static files via HTTP?

Spread the love

Sometimes, we want to create a quick file server with Node.js to server static files via HTTP.

In this article, we’ll look at how to create a quick file server with Node.js to server static files via HTTP.

How to create a quick file server with Node.js to server static files via HTTP?

To create a quick file server with Node.js to server static files via HTTP, we can use the http, final-handler and serve-static packages.

For instance, we write

const http = require('http');
const finalhandler = require('finalhandler');
const serveStatic = require('serve-static');

const serve = serveStatic("./");

const server = http.createServer((req, res) => {
  const done = finalhandler(req, res);
  serve(req, res, done);
});

to call serveStatic with the path of the folder we want to serve files from.

Then we create the HTTP server with http.createServer with a callback that calls finalhandler to return the done function which runs when the request processing is done.

And then we call serve with the request req object, response res object, and the done function.

Conclusion

To create a quick file server with Node.js to server static files via HTTP, we can use the http, final-handler and serve-static packages.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *