Use @chubbyts/chubbyts-undici-server on node.js.
- node: 20
- @chubbyts/chubbyts-undici-server: ^1.0.1
Through NPM as @chubbyts/chubbyts-undici-server-node.
npm i @chubbyts/chubbyts-undici-server-node@^1.0.1import { STATUS_CODES } from 'node:http';
import type { Server } from 'node:http';
import { createServer } from 'node:http';
import type { Handler, ServerRequest } from '@chubbyts/chubbyts-undici-server/dist/server';
import { Response } from '@chubbyts/chubbyts-undici-server/dist/server';
import {
createNodeRequestToUndiciRequestFactory,
createUndiciResponseToNodeResponseEmitter,
} from '@chubbyts/chubbyts-undici-server-node/dist/node';
const serverHost = process.env.SERVER_HOST as string;
const serverPort = parseInt(process.env.SERVER_PORT as string);
const shutdownServer = (server: Server) => {
server.close((err) => {
if (err) {
console.warn(`Shutdown server with error: ${err}`);
process.exit(1);
}
console.log('Shutdown server');
process.exit(0);
});
};
const nodeRequestToUndiciRequestFactory = createNodeRequestToUndiciRequestFactory('https://example.com');
// for example @chubbyts/chubbyts-framework app (which implements Handler)
const handler: Handler = async (serverRequest: ServerRequest<{name: string}>): Promise<Response> => {
return new Response(`Hello, ${serverRequest.attributes.name}`, {
status: 200,
statusText: STATUS_CODES[200],
headers: {'content-type': 'text/plain'}
});
};
const undiciResponseToNodeResponseEmitter = createUndiciResponseToNodeResponseEmitter();
const server = createServer(async (req, res) => {
const serverRequest = nodeRequestToUndiciRequestFactory(req);
const response = await handler(serverRequest);
undiciResponseToNodeResponseEmitter(response, res);
});
server.listen(serverPort, serverHost, () => {
console.log(`Listening to ${serverHost}:${serverPort}`);
});
process.on('SIGINT', () => shutdownServer(server));
process.on('SIGTERM', () => shutdownServer(server));2025 Dominik Zogg