Proper way to define a main() script in Deno
Asked Answered
R

1

7

When writing a Deno script, sometimes they could be a executed from the command line using deno run but at the same time may contain libraries that can be consumed through an import from another script.

What is the proper way to do this in Deno.

The equivalent in Python would be to put at the bottom of the script:

if __name__ == '__main__':
    main(sys.argv[1:])

How should this be done in Deno?

Renault answered 15/5, 2020 at 23:31 Comment(0)
R
9

Deno has a flag available at runtime called import.meta.main. Here is an example of how it should be used in a script:

if (import.meta.main) main()
// bottom of file

From the docs:

Deno supports a number of methods on the import.meta API:

import.meta.url: returns the URL of the current module.
import.meta.main: returns whether the current module is the entry point to your program.
import.meta.resolve: resolve specifiers relative to the current module.

Note: import namespace is not available in the Deno REPL at v1.0.0

Renault answered 15/5, 2020 at 23:31 Comment(1)
Yeah, this is also how they do it in the Deno docs in the example "Testing if current file is the main program".Stayathome

© 2022 - 2024 — McMap. All rights reserved.