On this page
deno serve
deno serve 使用 Deno.serve() 将一个文件作为 HTTP 服务器运行。该文件必须导出一个带有 fetch 处理器的默认对象。有关构建 HTTP 服务器的完整指南,请参阅 编写 HTTP 服务器。
基本用法 Jump to heading
export default {
fetch(_req: Request) {
return new Response("Hello world!");
},
} satisfies Deno.ServeDefaultExport;
deno serve server.ts
默认情况下,服务器监听 8000 端口。可以使用 --port 覆盖它:
deno serve --port=3000 server.ts
默认导出结构 Jump to heading
该文件必须导出一个默认对象,该对象满足
Deno.ServeDefaultExport。该对象包含
两个属性:
export interface ServeDefaultExport {
fetch: ServeHandler;
onListen?: (localAddr: Deno.Addr) => void;
}
fetch(必需) Jump to heading
fetch 处理器接收一个标准的
Request 以及一个携带连接元数据的
ServeHandlerInfo 对象:
type ServeHandler = (
request: Request,
info: ServeHandlerInfo,
) => Response | Promise<Response>;
interface ServeHandlerInfo {
remoteAddr: Deno.Addr; // 连接的远程地址
completed: Promise<void>; // 在请求完成时解析
}
如果处理器抛出错误,错误会被隔离到该请求——服务器会继续提供服务。
onListen(可选) Jump to heading
当服务器开始监听时会调用一次。如果省略,将记录默认消息到控制台。
export default {
fetch(request, info) {
const { hostname, port } = info.remoteAddr as Deno.NetAddr;
console.log(`${request.method} ${request.url} from ${hostname}:${port}`);
return new Response("Hello, World!", {
headers: { "content-type": "text/plain" },
});
},
onListen({ hostname, port }) {
console.log(`Server running at http://${hostname}:${port}/`);
},
} satisfies Deno.ServeDefaultExport;
默认导出对象上的任何其他属性都会被静默忽略。如果缺少 fetch,
则不会启动服务器。如果 fetch 或 onListen 存在但不是函数,
将抛出 TypeError。
路由请求 Jump to heading
使用请求 URL 将请求路由到不同的处理器:
export default {
fetch(request: Request) {
const url = new URL(request.url);
if (url.pathname === "/api/health") {
return Response.json({ status: "ok" });
}
return new Response("Not found", { status: 404 });
},
} satisfies Deno.ServeDefaultExport;
绑定到主机名 Jump to heading
默认情况下,deno serve 监听 0.0.0.0。使用 --host 绑定到特定接口:
deno serve --host=127.0.0.1 server.ts
水平扩展 Jump to heading
跨多个 CPU 核心运行多个服务器实例,以获得更好的吞吐量:
deno serve --parallel server.ts
监视模式 Jump to heading
当文件发生更改时自动重启服务器:
deno serve --watch server.ts
权限 Jump to heading
deno serve 会自动允许服务器监听,无需 --allow-net。其他权限(例如文件读取)必须显式授予:
deno serve --allow-read server.ts
deno serve [OPTIONS] [SCRIPT_ARG]...Run a server defined in a main module
The serve command uses the default exports of the main module to determine which servers to start.
Start a server defined in server.ts:
deno serve server.ts
Start a server defined in server.ts, watching for changes and running on port 5050:
deno serve --watch --port 5050 server.ts
Type checking options Jump to heading
--check<CHECK_TYPE>optionalEnable type-checking. This subcommand does not type-check by default If the value of "all" is supplied, remote modules will be included. Alternatively, the 'deno check' subcommand can be used.
--no-check<NO_CHECK_TYPE>optionalSkip type-checking. If the value of "remote" is supplied, diagnostic errors from remote modules will be ignored.
Dependency management options Jump to heading
--cached-onlyRequire that remote dependencies are already cached.
--frozen<BOOLEAN>optionalError out if lockfile is out of date.
Load import map file from local file or remote URL.
--lock<FILE>optionalCheck the specified lock file. (If value is not provided, defaults to "./deno.lock").
--no-lockDisable auto discovery of the lock file.
--no-npmDo not resolve npm modules.
--no-remoteDo not resolve remote modules.
--node-modules-dir<MODE>optionalSets the node modules management mode for npm packages.
--reload, -r<CACHE_BLOCKLIST>optionalReload source code cache (recompile TypeScript) no value Reload everything jsr:@std/http/file-server,jsr:@std/assert/assert-equals Reloads specific modules npm: Reload all npm modules npm:chalk Reload specific npm module.
--vendor<vendor>optionalToggles local vendor folder usage for remote modules and a node_modules folder for npm packages.
Options Jump to heading
--allow-scripts<PACKAGE>optionalAllow running npm lifecycle scripts for the given packages
Note: Scripts will only be executed when using a node_modules directory (--node-modules-dir).
--cert<FILE>Load certificate authority from PEM encoded file.
--conditions<conditions>Use this argument to specify custom conditions for npm package exports. You can also use DENO_CONDITIONS env var. .
Configure different aspects of deno including TypeScript, linting, and code formatting.
Typically the configuration file will be called deno.json or deno.jsonc and
automatically detected; in that case this flag is not necessary.
--cpu-profStart the V8 CPU profiler on startup and write the profile to disk on exit. Profiles are written to the current directory by default.
--cpu-prof-dir<DIR>Directory where the V8 CPU profiles will be written. Implicitly enables --cpu-prof.
--cpu-prof-flamegraphGenerate an SVG flamegraph alongside the CPU profile.
--cpu-prof-interval<MICROSECONDS>Sampling interval in microseconds for CPU profiling (default: 1000).
--cpu-prof-mdGenerate a human-readable markdown report alongside the CPU profile.
--cpu-prof-name<NAME>Filename for the CPU profile (defaults to CPU.
--env-file<FILE>optionalLoad environment variables from local file Only the first environment variable with a given key is used. Existing process environment variables are not overwritten, so if variables with the same names already exist in the environment, their values will be preserved. Where multiple declarations for the same environment variable exist in your .env file, the first one encountered is applied. This is determined by the order of the files you pass as arguments.
--ext<ext>Set content type of the supplied file.
--host<host>The TCP address to serve on, defaulting to 0.0.0.0 (all interfaces).
--location<HREF>Value of globalThis.location used by some web APIs.
--minimum-dependency-age<minimum-dependency-age>(Unstable) The age in minutes, ISO-8601 duration or RFC3339 absolute timestamp (e.g. '120' for two hours, 'P2D' for two days, '2025-09-16' for cutoff date, '2025-09-16T12:00:00+00:00' for cutoff time, '0' to disable).
--no-code-cacheDisable V8 code cache feature.
--no-configDisable automatic loading of the configuration file.
--openOpen the browser on the address that the server is running on.
--parallelRun multiple server workers in parallel. Parallelism defaults to the number of available CPUs or the value of the DENO_JOBS environment variable.
--port<port>The TCP port to serve on. Pass 0 to pick a random free port [default: 8000]
--preload<FILE>A list of files that will be executed before the main module.
--require<FILE>A list of CommonJS modules that will be executed before the main module.
--seed<NUMBER>Set the random number generator seed.
--tunnel, -t<tunnel>optionalExecute tasks with a tunnel to Deno Deploy.
Create a secure connection between your local machine and Deno Deploy, providing access to centralised environment variables, logging, and serving from your local environment to the public internet.
--v8-flags<V8_FLAGS>optionalTo see a list of all available flags use --v8-flags=--help
Flags can also be set via the DENO_V8_FLAGS environment variable.
Any flags set with this flag are appended after the DENO_V8_FLAGS environment variable.
Debugging options Jump to heading
--inspect<HOST_PORT>optionalActivate inspector on host:port [default: 127.0.0.1:9229]. Host and port are optional. Using port 0 will assign a random free port.
--inspect-brk<HOST_PORT>optionalActivate inspector on host:port, wait for debugger to connect and break at the start of user script.
--inspect-wait<HOST_PORT>optionalActivate inspector on host:port and wait for debugger to connect before running user code.
File watching options Jump to heading
--no-clear-screenDo not clear terminal screen when under watch mode.
--watch<FILES>optionalWatch for file changes and restart process automatically. Local files from entry point module graph are watched by default. Additional paths might be watched by passing them as arguments to this flag.
--watch-exclude<FILES>optionalExclude provided files/patterns from watch mode.
--watch-hmr<FILES>optionalWatch for file changes and restart process automatically. Local files from entry point module graph are watched by default. Additional paths might be watched by passing them as arguments to this flag.