Skip to content

suggestion: add way to check if deno serve is being run #29447

Open
@iuioiua

Description

@iuioiua

Problem

Ignoring wrappers, Deno.serve() is typically used this way:

if (import.meta.main) {
  Deno.serve(handler);
}

If one wants to add the ability to use deno serve, they'll have to export handler() and create another entrypoint, as there's currently no way to know if deno run or deno serve is being used, and import.meta.main is true for both subcommands. In other words, a single entrypoint can only work with one or the other subcommands.

Suggested solution

I suggest adding a Deno.isServe: boolean that evaluates to true when deno serve is being run and false when deno serve is not being run. By doing so, one can make a trivial change to their existing endpoint that uses Deno.serve() that allows them to use both deno run and deno serve without having to make breaking changes.

- if (import.meta.main) {
+ if (import.meta.main && !Deno.isServe) {
    Deno.serve(handler);
  }

+ export default {
+   fetch: handler,
+ } satisfies Deno.ServeDefaultExport;

Expanding on that idea, I wonder whether there are other situations where knowing the current subcommand being run is worthwhile. E.g. someone wants test and implementation code within the same file, but the test code requires setup logic. It might be a niche use case. Maybe even no one would think to do that. If it is the case that knowing the subcommand is worthwhile, we can add something like:

Deno.isExecuted(subcommand: "run" | "bench" | "test"...);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions