Create api using bun
Building a Simple HTTP Server with Bun: A Modern JavaScript Runtime
JavaScript runtimes have evolved significantly over the years, and Bun is one of the latest, fastest, and most exciting options available. In this blog, I'll walk you through building a simple HTTP server using Bun. We'll also log requests to a file, making this a practical example of Bun's powerful features.
Why Use Bun?
Bun is a modern JavaScript runtime designed to be faster and more efficient than traditional tools like Node.js. With built-in support for TypeScript, NPM packages, and ultra-fast APIs for HTTP servers, file systems, and more, Bun is the ideal runtime for modern JavaScript applications.
Some key benefits of using Bun:
Speed: It's one of the fastest JavaScript runtimes.
Built-in Modules: Includes support for HTTP servers, file operations, and more, out of the box.
TypeScript Support: No additional setup is needed for TypeScript.
Simple and Lightweight: Fewer dependencies are required compared to Node.js.
Setting Up Bun
Before diving into the code, ensure you have Bun installed on your system. If you haven’t installed Bun yet, run the following command:
curl -fsSL https://bun.sh/install | bash
Once installed, verify the installation by running:
bun --version
Writing the HTTP Server with Bun:
Here's the complete code for creating an HTTP server with Bun. The server handles multiple routes and logs all requests to a log.txt file.
import { serve } from 'bun';
import { writeFileSync, appendFileSync } from 'bun';
const PORT = 8050;
const LOG_FILE = 'log.txt';
// Log requests to a file
const logRequest = (url) => {
const timestamp = new Date().toISOString();
const logEntry = `${timestamp} - Request URL: ${url}\n`;
appendFileSync(LOG_FILE, logEntry, 'utf-8');
};
// Start the server
serve({
port: PORT,
fetch(req) {
logRequest(req.url);
switch (req.url) {
case '/':
return new Response('Welcome to the BarterX');
case '/products':
return new Response('Here are the products up for Sale in BarterX');
case '/login':
return new Response('Login to the BarterX');
case '/signup':
return new Response('Sign up to the BarterX');
case '/profile':
return new Response('Trader Profile');
case '/cart':
return new Response('Your Shopping Cart is here');
case '/checkout':
return new Response("Let's start shipping");
case '/orders':
return new Response('Your Orders are here');
case '/categories':
return new Response('Browse Categories');
case '/chat':
return new Response('Your Chat with fellow Traders');
case '/contact':
return new Response('Contact Us at');
case '/about':
return new Response('The modern approach to trading our commodities');
default:
const error = {
error: 'Page not found',
statusCode: 404,
};
return new Response(JSON.stringify(error), {
status: 404,
headers: { 'Content-Type': 'application/json' },
});
}
},
});
console.log(`Server running on http://localhost:${PORT}...`);
Code Walkthrough
1. Logging Requests
The logRequest function logs all incoming requests to a log.txt file. Using Bun's appendFileSync method ensures that each log entry is appended to the file efficiently.
2. Handling Routes
We use Bun's serve function to create an HTTP server. The fetch method processes incoming requests and handles various routes like /, /products, /login, and more.
Example of route handling
3. Error Handling
For unknown routes, we return a 404 error with a JSON response
Running the Server
Save the code in a file called server.js and run it with Bun:
bun server.js
Open your browser and navigate to http://localhost:8050/. Try out different routes like /products, /login, or /about. You’ll see the appropriate responses. For any undefined route, a 404 JSON error will be returned.
