Using npx http-server
Introduction
http-server is a simple, zero-configuration command-line HTTP server that can serve static
files. It is useful for serving web applications during development and testing. You can
quickly set it up using npx, which allows you to run Node.js packages without installing them
globally.
Prerequisites
Ensure you have Node.js installed. You can download it from nodejs.org.
Basic understanding of the command line.
Setting Up a Simple HTTP Server with npx
1. Create a Project Directory
First, create a directory for your project and navigate into it:
mkdir my-http-server
cd my-http-server
2. Create Some Static Files
Create an index.html file in your project directory:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My HTTP Server</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is served using http-server.</p>
</body>
</html>
You can create additional files (like CSS or JavaScript) as needed.
3. Start the HTTP Server
You can start the server using npx:
npx http-server
By default, this command will serve the files in the current directory on port 8080. You
should see output similar to:
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://<your-ip-address>:8080
Hit CTRL-C to stop the server
4. Accessing the Server
Open your web browser and go to http://localhost:8080. You should see your
index.html file being served, displaying "Hello, World!" and the accompanying text.
5. Customizing the Server
You can customize the behavior of http-server with various command-line options. Here
are a few common options:
Change the Port: To serve on a different port, use the -p option:
npx http-server -p 3000
Specify a Custom Root Directory: Use the -d option to specify a directory:
npx http-server ./public -p 3000
Enable CORS: Use the --cors option to enable Cross-Origin Resource Sharing:
npx http-server --cors
Show Directory Listings: If you want to enable directory listing, use the -a option:
npx http-server -a localhost
6. Stopping the Server
To stop the server, simply go back to your terminal and press CTRL + C.
Conclusion
Using npx http-server is a quick and easy way to serve static files for development
purposes. Its simplicity and flexibility make it a great tool for quickly testing web applications
without the need for complex configurations. Whether you are working on a simple static site
or a more complex project, http-server can help streamline your workflow.