Command
Yes, Milkio can be used not only to build servers behind the client side, but also to develop small tools that can be used in the terminal.
Writing
Any API located in the /apps/$/
directory is treated as a command. When using commands, it feels like using a regular API, with the difference being the format of the parameters. Create a /apps/$/say.ts
file and try saying hello to the world…?
You may notice that you now have two parameters: commands
and options
. These parameters are automatically parsed from argv
by Milkio. Take a look at the following example, which shows the executed command and the obtained params.
Usage
Before bundling, we can use our command with bun command
.
We can also bundle our application into a binary file. In the scripts
section of our /package.json
, modify the build
script to bundle our command instead of the HTTP server.
Run the build command, and you will have a new file named app
in your directory.
Try running it!
Default Command
When executed directly, Milkio will try to find a command named default
.
For example, when running ./app
or bun command
, it will actually execute your /src/apps/$/default.ts
file.
Command Not Found
When a command is not found, Milkio will execute the notFoundHandler
method defined in your /run-command.ts
file. The event object contains the executed command name and any accompanying params.
Interactive CLI
Bun provides built-in methods for creating an interactive CLI.
$ Shell
Bun’s $ Shell feature is very powerful.
Get the output of a shell command as text:
Pass parameters:
To avoid potential security issues, Bun’s $ Shell parameterizes template string interpolation. This means that the following approach will not work as expected:
You can use raw
to disable this protection:
For more usage, please refer to the $ Shell documentation.
Starting an HTTP Server with a Command
Sometimes, we may need to develop an application that includes both commands and an HTTP server, and start the HTTP server with a specific command.
Thanks to Milkio’s excellent modularity, it’s easy to combine the two. You just need to copy the code from /run-serve.ts
into your command.