Serve Local Files and Folders from any Directory with Node Based Web Server
A lot of times we just want to quickly serve a directory full of static assets over a web server so that we could quickly do some testing in the browser. Instead of setting up a full blown web server like Apache or Nginx and configuring it accordingly, we could simply use the
http-server Node.js module.
http-server is a simple, zero-configuration command line HTTP server that is used to serve static content like html, css, js, image, video, font, etc. files. It is super simple to install and use it for local development and testing purposes.
To use the
http-server package make sure you have node installed on your system that ships with the npm package manager. With that in place, install the module like this:
# Globally via npm $ npm install -g http-server # As an npm dependency which can then be used with # npm run (scripts), npm exec, npx $ npm install http-server # For macOS users, brew is also an option $ brew install http-server
Once the package is installed you can use it like any other executable from your terminal:
# usage: http-server [path] [options] # If it was installed with -g $ http-server # If it was installed locally, then you could $ npm exec http-server # or $ npx http-server
I personally love just using
# Fetch the package remotely (if not installed locally) and run the command $ npx http-server Starting up http-server, serving ./ http-server version: 14.1.0 http-server settings: CORS: disabled Cache: 3600 seconds Connection Timeout: 120 seconds Directory Listings: visible AutoIndex: visible Serve GZIP Files: false Serve Brotli Files: false Default File Extension: none Available on: <http://127.0.0.1:8080> <http://192.168.189.92:8080> Hit CTRL-C to stop the server
By default, the command
http-server will start serving the current working directory at
http://0.0.0.0:8080. You can easily configure the host and port like this:
$ npx http-server -a localhost -p 9090
It provides a bunch of other options as well for configuring, feel free to go through them by executing
npx http-server --help.