Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
The h3 npm package is a high-performance HTTP framework for Node.js, designed to be lightweight and fast. It is often used for building APIs and microservices, providing a simple and efficient way to handle HTTP requests and responses.
Basic HTTP Server
This code demonstrates how to create a basic HTTP server using the h3 package. The server listens on port 3000 and responds with 'Hello, world!' to any incoming requests.
const { createApp } = require('h3');
const { createServer } = require('http');
const app = createApp();
app.use('/', (req, res) => {
res.end('Hello, world!');
});
createServer(app).listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Middleware Support
This example shows how to use middleware with the h3 package. The middleware logs each incoming request's method and URL before passing control to the next handler.
const { createApp } = require('h3');
const { createServer } = require('http');
const app = createApp();
// Middleware to log requests
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use('/', (req, res) => {
res.end('Hello, world!');
});
createServer(app).listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Routing
This code demonstrates how to set up routing with the h3 package. It defines GET and POST routes for the '/hello' path, responding with different messages based on the HTTP method.
const { createApp, useRouter } = require('h3');
const { createServer } = require('http');
const app = createApp();
const router = useRouter();
router.get('/hello', (req, res) => {
res.end('Hello, GET!');
});
router.post('/hello', (req, res) => {
res.end('Hello, POST!');
});
app.use(router);
createServer(app).listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Express is a widely-used web application framework for Node.js, known for its simplicity and flexibility. It provides robust routing, middleware support, and a wide range of HTTP utility methods. Compared to h3, Express is more feature-rich and has a larger community, but it may be heavier and less performant for certain use cases.
Koa is a next-generation web framework for Node.js, created by the same team behind Express. It uses async functions to simplify middleware and improve error handling. Koa is more modular and lightweight compared to Express, similar to h3, but it requires more boilerplate code to set up.
Fastify is a web framework for Node.js that focuses on performance and low overhead. It provides a schema-based validation system and a powerful plugin architecture. Fastify is similar to h3 in terms of performance and simplicity, but it offers more built-in features and a more extensive plugin ecosystem.
What?
aync/await
supportSee un for workers support
yarn add h3
# or
npm install h3
Using listhen:
const { createApp } = require('h3')
const { listen } = require('listhen')
const app = createApp()
app.use('/', () => 'Hello world!')
listhen(app)
Using plain node:
const { Server } = require('http')
const { createApp } = require('h3')
const app = createApp()
// Handle can directly return object or Promise<object> for JSON response
app.use('/api', (req) => ({ url: req.url }))
// You can have better matching other than quick prefix match
app.use('/odd', () => 'Is odd!', { match: url => url.substr(1) % 2 })
// Handle can directly return string for HTML response
app.use(() => '<h1>Hello world!</h1>')
// You can chain calls to .use()
app.use('/1', () => '<h1>Hello world!</h1>').use('/2', () => '<h1>Goodbye!</h1>')
// If handle is already async, using useAsync to avoid unnecessary promisify wrapper
// (Shortcut to pass { promisify: false })
// app.useAsync(async () => {})
// Lazy loading routes using { lazy: true }
// app.use('/big', () => import('./big'), { lazy: true })
const port = process.env.PORT || 3000
const server = new Server(app)
server.listen(port, () => {
console.log(`Listening on: http://localhost:${port}`)
})
There are two vital parts that make it working: Stack Runner (App
), and promisifyHandle
.
App is basically a http server handle with req, res
and attached utilities that runs a stack
of middleware/handles in parallel. It will stop when the writableEnded
flag is set on a response
(which means that res.end
has been called) and throw a 404 if writableEnded
flag has not been set by the end.
Additionally the app has a quick prefix matcher and will automatically call res.end
if any stack layers return a value.
promisifyHandle
Converts a classic middleware (req, res, next?
) into a promisified version ready to use with App
resolve/reject
when calledclose
and error
events of res, promise will resolve/reject
(to ensure if middleware simply calls res.end
)When calling app.use
, middleware will be automatically promisified.
If you are already making an async aware middleware, you can use app.useAsync
MIT
FAQs
Minimal H(TTP) framework built for high performance and portability.
The npm package h3 receives a total of 891,569 weekly downloads. As such, h3 popularity was classified as popular.
We found that h3 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.