jsrosetta

I/O

HTTP Server

http.createServer của Node.js so với ServeMux (Go 1.22+), axum (Rust), Network.framework (Swift) và HttpServer (Java) để viết HTTP server có route.

Phiên bản tối thiểu
Node.js ≥ 18Go ≥ 1.22Rust ≥ 1.85Swift ≥ 5.7Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Node.js và Go có HTTP server ngay trong standard library, không cần framework để bắt đầu. Rust std thì không — cần một crate như axum (routing + path param gọn như ServeMux của Go). Swift cũng vậy: Foundation không có HTTP server, ví dụ dưới đây tự parse dòng request đầu tiên qua Network.framework — đủ cho demo, không phải một HTTP server đúng chuẩn. Java có com.sun.net.httpserver.HttpServer (module jdk.httpserver) từ lâu, khớp path theo tiền tố thay vì pattern có wildcard.

Server có route

import http from 'node:http'
 
function handler(request, response) {
  response.writeHead(200, { 'Content-type':'text/plain' })
  response.write('hello world')
  response.end()
}
 
const server = http.createServer(handler)
server.listen(8080)
$ curl http://localhost:8080
hello world

Client (http_client.js, chạy trong khi một server ở trên đang bật): fetch() toàn cục thay cho http.get()/http.request() cho các request đơn giản.

const response = await fetch('http://localhost:8080')
console.log(await response.text())
$ node http_client.js
hello world
# chỉ áp dụng cho các server có route /hello/{name} (Go, Rust, Swift, Java) — JS server ở trên không có route này
$ curl http://localhost:8080/hello/gopher
hello gopher

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#http-server