I want to use some of the Deno standard libraries in Node.js to create an HTTP server.
I know that I can just download it but I want to stay updated with the latest library so I want to import them like this:
import { serve } from "https://deno.land/std/http/server.ts";
// Defining port to be used
const PORT = 8080
// Setting server to listen at port
const server = serve({ port: PORT });
console.log(`This Hello World server is up and running on http://localhost:${PORT}/`);
// Sending Hello World to any client that connects
for await (const req of server) {
req.respond({ body: "Hello World!\n" });
}
CodePudding user response:
It's theoretically possible to use a limited subset of the Deno std library in Node (modules which use nothing from the web APIs, nothing from the Deno API, and include no import statements with specifiers ending in .ts).
However, the module from your example at https://deno.land/std/http/server.ts does not meet this criteria and will create both compile-time errors in tsc (TypeScript) and runtime errors in Node.js.
CodePudding user response:
Nevermind I just want to use ES6 syntax to create a server so I use this:
import https from "https";
import http from "http";
export default class Server {
readonly server: http.Server | https.Server;
constructor(options?: http.ServerOptions | https.ServerOptions, httpsMode?: boolean) {
this.server = (httpsMode ? https : http).createServer(options);
}
listen(port?: number, hostname?: string, backlog?: number) {
let s = this.server;
s.listen(port, hostname, backlog);
return {
[Symbol.asyncIterator]() {
return {
async next() {
return {
done: false,
value: await new Promise<{request: http.IncomingMessage, response: http.ServerResponse}>(result => {
s.on('request', (request, response) =>
result({request, response})
);
})
};
}
}
}
}
}
close() {
this.server.close();
}
}
This module is available on NPM, package Newer.js after I publish 0.0.4
